### Quick Start: Define Django models, Strawberry types, schema, and URL Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/README.md Quick start setup for a Strawberry Django GraphQL API. Create models.py, types.py, schema.py, and urls.py as shown. The schema uses DjangoOptimizerExtension to prevent N+1 queries and AsyncGraphQLView to serve the API at /graphql/. ```python # models.py from django.db import models class Fruit(models.Model): name = models.CharField(max_length=20) color = models.ForeignKey("Color", on_delete=models.CASCADE, related_name="fruits") class Color(models.Model): name = models.CharField(max_length=20) ``` ```python # types.py import strawberry_django from strawberry import auto from . import models @strawberry_django.type(models.Fruit) class Fruit: id: auto name: auto color: "Color" @strawberry_django.type(models.Color) class Color: id: auto name: auto fruits: list[Fruit] ``` ```python # schema.py import strawberry import strawberry_django from strawberry_django.optimizer import DjangoOptimizerExtension from .types import Fruit @strawberry.type class Query: fruits: list[Fruit] = strawberry_django.field() schema = strawberry.Schema( query=Query, extensions=[DjangoOptimizerExtension], ) ``` ```python # urls.py from django.urls import path from strawberry.django.views import AsyncGraphQLView from .schema import schema urlpatterns = [ path("graphql/", AsyncGraphQLView.as_view(schema=schema)), ] ``` -------------------------------- ### Clone repository and install pre-commit hooks Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/README.md Clone the repository and install pre-commit hooks for contributing. After this, run tests with `make test` or `make test-dist`. ```shell git clone https://github.com/strawberry-graphql/strawberry-django cd strawberry-django pre-commit install ``` -------------------------------- ### HasPerm extension examples Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/docs/guide/permissions.md Examples showing how to require all permissions, allow superusers to bypass, and raise errors instead of returning None. ```python # Require ALL permissions @strawberry_django.field( extensions=[HasPerm(["app.view_model", "app.change_model"], any_perm=False)] ) def sensitive_field(self) -> str: ... # Allow superusers to bypass @strawberry_django.field( extensions=[HasPerm("app.special_permission", with_superuser=True)] ) def special_field(self) -> str: ... # Raise error instead of returning None @strawberry_django.field( extensions=[HasPerm("app.required_permission", fail_silently=False)] ) def required_field(self) -> str: ... ``` -------------------------------- ### Install strawberry-graphql-django Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/README.md Install the strawberry-graphql-django package from PyPI. ```shell pip install strawberry-graphql-django ``` -------------------------------- ### ASGI and Daphne setup for subscriptions Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/docs/guide/troubleshooting.md Set up ASGI with AuthGraphQLProtocolTypeRouter and configure Daphne and ASGI_APPLICATION for subscriptions. ```python import os from django.core.asgi import get_asgi_application from strawberry_django.routers import AuthGraphQLProtocolTypeRouter os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings") django_asgi_app = get_asgi_application() from .schema import schema application = AuthGraphQLProtocolTypeRouter( schema, django_application=django_asgi_app, ) ``` ```python INSTALLED_APPS = [ "daphne", # Must be before 'django.contrib.staticfiles' "django.contrib.staticfiles", # ... ] ASGI_APPLICATION = "project.asgi.application" ``` -------------------------------- ### Install dependencies with poetry install Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/examples/ecommerce_app/README.md Installs project dependencies using Poetry. ```shell poetry install ``` -------------------------------- ### Install Daphne Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/docs/guide/subscriptions.md Install Daphne, the ASGI server that overrides the runserver command to support ASGI. This is required for local testing of subscriptions. ```bash pip install daphne ``` -------------------------------- ### Complete example schema with queries and mutations Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/docs/index.md A complete Strawberry Django schema showing a Query with filtering and pagination, a Mutation with CRUD operations and error handling, and the schema setup with DjangoOptimizerExtension. Includes example GraphQL queries for fetching, filtering, creating, and updating fruits. ```python import strawberry from strawberry_django import mutations from strawberry_django.optimizer import DjangoOptimizerExtension from strawberry_django.pagination import OffsetPaginationInput from strawberry.permission import BasePermission from strawberry.types import Info from typing import Optional from .types import Fruit, Color from . import models class IsAuthenticated(BasePermission): message = "User is not authenticated" def has_permission(self, source, info: Info, **kwargs) -> bool: return info.context.request.user.is_authenticated @strawberry.type class Query: @strawberry_django.field def fruits( self, category: Optional[str] = None, pagination: Optional[OffsetPaginationInput] = None, ) -> list[Fruit]: """Get fruits with optional filtering and pagination""" queryset = models.Fruit.objects.all() if category: queryset = queryset.filter(category=category) if pagination: queryset = queryset[ pagination.offset : pagination.offset + pagination.limit ] else: queryset = queryset[:20] return queryset @strawberry_django.field def fruit(self, id: strawberry.ID) -> Optional[Fruit]: """Get a single fruit by ID""" return models.Fruit.objects.filter(id=id).first() @strawberry_django.field def colors(self) -> list[Color]: """Get all colors""" return models.Color.objects.all() @strawberry.type class Mutation: # CRUD operations with automatic error handling create_fruit: Fruit = mutations.create(FruitInput, handle_django_errors=True) update_fruit: Fruit = mutations.update(FruitInputPartial, handle_django_errors=True) @strawberry.mutation(permission_classes=[IsAuthenticated]) def delete_fruit(self, info: Info, id: strawberry.ID) -> bool: """Delete a fruit (requires authentication)""" models.Fruit.objects.filter(id=id).delete() return True schema = strawberry.Schema( query=Query, mutation=Mutation, extensions=[ DjangoOptimizerExtension, # Prevents N+1 queries ], ) ``` ```graphql # Get all fruits with their colors query GetAllFruits { fruits { id name category displayName color { name } } } # Get filtered and paginated fruits query GetBerries { fruits(category: "BERRY", pagination: { offset: 0, limit: 5 }) { name color { name } } } # Create a new fruit mutation CreateFruit { createFruit(data: { name: "Raspberry", category: "BERRY", colorId: "1" }) { ... on Fruit { id name category } ... on OperationInfo { messages { field message kind } } } } # Update a fruit mutation UpdateFruit { updateFruit(id: "1", data: { name: "Updated Strawberry" }) { ... on Fruit { id name } ... on OperationInfo { messages { field message } } } } ``` -------------------------------- ### Install channels and daphne Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/docs/integrations/channels.md Install the required packages for Django Channels integration. ```bash pip install channels daphne ``` -------------------------------- ### Install channels-redis for Redis-backed channel layers Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/docs/integrations/channels.md Optional package for production deployments requiring a Redis-backed channel layer. ```bash pip install channels-redis # For Redis-backed channel layers ``` -------------------------------- ### Run the development server with manage.py runserver Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/examples/ecommerce_app/README.md Starts the Django development server; GraphiQL available at http://localhost:8000/graphql/. ```shell poetry run python manage.py runserver ``` -------------------------------- ### Basic TestClient query example Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/docs/guide/unit-testing.md Shows how to instantiate TestClient with a GraphQL endpoint path and execute a query, asserting no errors and expected data. ```python from strawberry_django.test.client import TestClient def test_query(db): client = TestClient("/graphql") response = client.query(""" query { fruits { id name } } """) assert response.errors is None assert response.data == {"fruits": [{"id": "1", "name": "Apple"}]} ``` -------------------------------- ### Install django-guardian Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/docs/integrations/guardian.md Install django-guardian via pip, either alone or with the strawberry-django extras. ```bash pip install django-guardian ``` ```bash pip install strawberry-graphql-django pip install django-guardian ``` -------------------------------- ### Install strawberry-graphql-django with poetry Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/docs/index.md Install the strawberry-graphql-django package using poetry. The second command installs django-choices-field, which is recommended but not required. For non-poetry users, pip install strawberry-graphql-django works fine. ```sh poetry add strawberry-graphql-django poetry add django-choices-field # Not required but recommended ``` -------------------------------- ### Paginate list queries with OffsetPaginationInput Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/docs/guide/performance.md Shows a bad example returning an unbounded list and a good example using OffsetPaginationInput with a default offset of 0 and limit of 20 to paginate results. ```python # Bad: Unbounded lists @strawberry.field def books(self) -> List[BookType]: return Book.objects.all() # Could return millions! # Good: Always paginate @strawberry.field def books( self, pagination: OffsetPaginationInput = OffsetPaginationInput(offset=0, limit=20) ) -> List[BookType]: return Book.objects.all()[pagination.offset : pagination.offset + pagination.limit] ``` -------------------------------- ### Example: Export schema to file Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/docs/guide/export-schema.md Exports the schema located at myapp.schema to the file output/schema.graphql. ```sh python manage.py export_schema myapp.schema --path=output/schema.graphql ``` -------------------------------- ### Apply permission extensions to connections Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/examples/ecommerce_app/README.md Shows how to apply permission extensions to connections. The first example restricts to authenticated users, the second to staff users. ```python # Only authenticated users @strawberry_django.connection(extensions=[IsAuthenticated()]) def my_orders(self, info: Info) -> Iterable[Order]: ... # Only staff users orders_conn: DjangoListConnection[OrderType] = strawberry_django.connection( extensions=[IsStaff()] ) ``` -------------------------------- ### GraphQL Mutation Example Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/docs/guide/nested-mutations.md GraphQL mutation demonstrating the usage of the createAuthorWithBooks mutation with nested book data. ```graphql mutation CreateAuthorWithBooks { createAuthorWithBooks( data: { name: "Jane Smith" email: "jane@example.com" books: [ { title: "Book One", publishedDate: "2024-01-01" } { title: "Book Two", publishedDate: "2024-06-01" } ] } ) { id name books { title } } } ``` -------------------------------- ### Run tests, lint, and type check with uv and ruff Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/AGENTS.md Commands for installing dependencies, running tests, linting, and type checking in the strawberry-django repository. Use `uv sync` to install dependencies, `uv run pytest` for the full test suite, and `uv run pytest -n auto` for parallel execution. Linting uses `ruff check` and `ruff format`, with `--fix` for auto-fixing, and type checking uses `pyright`. ```bash # Install dependencies uv sync # Run full test suite uv run pytest # Run tests in parallel uv run pytest -n auto # Run a single test file uv run pytest tests/test_optimizer.py -x # Run a specific test uv run pytest tests/test_optimizer.py::test_function_name -x # Lint (ruff check + format check) uv run ruff check . uv run ruff format --check . # Auto-fix lint issues uv run ruff check . --fix uv run ruff format . # Type checking uv run pyright ``` -------------------------------- ### GOOD: Using Async Helpers Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/examples/ecommerce_app/README.md Good example: using async helpers like aget_user() properly wraps the operation for async resolvers, avoiding SynchronousOnlyOperation. ```python # GOOD - Use async helpers async def my_resolver(self, info: Info): user = await info.context.aget_user() # Properly wrapped ``` -------------------------------- ### Run Development Server with runserver Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/docs/integrations/channels.md Run the server in development. With Daphne installed and configured, runserver automatically uses ASGI. ```bash python manage.py runserver ``` -------------------------------- ### Example subscription response Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/docs/guide/subscriptions.md Example JSON response from the count subscription, showing the final value (9) after the subscription completes. The count changes every 0.5 seconds up to a maximum of 9. ```json { "data": { "count": 9 } } ``` -------------------------------- ### Using with pytest-django Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/docs/guide/unit-testing.md Example usage of the test clients with pytest-django, showing how to use the db fixture. ```APIDOC ## Using with pytest-django ### Description Guidance for using the test clients with pytest-django, including the `db` fixture. ### Example ```python import pytest @pytest.mark.django_db def test_with_database(): client = TestClient("/graphql") # ... your test @pytest.mark.django_db @pytest.mark.asyncio async def test_async_with_database(): client = AsyncTestClient("/graphql") # ... your async test ``` ``` -------------------------------- ### Complete schema with DjangoOptimizerExtension and pagination Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/docs/guide/queries.md Complete schema example showing single-object, list, and custom queries with pagination, filters, and ordering. The schema enables DjangoOptimizerExtension and the GraphQL query demonstrates usage of pk, filters, order, and pagination arguments. ```python import strawberry import strawberry_django from strawberry_django.optimizer import DjangoOptimizerExtension from strawberry_django.pagination import OffsetPaginationInput from . import models from .types import Fruit, FruitFilter, FruitOrder @strawberry.type class Query: # Single object query with PK filter fruit: Fruit = strawberry_django.field() # List query with filters, ordering, and pagination @strawberry_django.field def fruits( self, filters: FruitFilter | None = strawberry.UNSET, order: FruitOrder | None = strawberry.UNSET, pagination: OffsetPaginationInput | None = None, ) -> list[Fruit]: qs = models.Fruit.objects.all() # Filters and ordering are applied automatically # when using strawberry_django.field # Apply pagination if pagination: qs = qs[pagination.offset : pagination.offset + pagination.limit] else: qs = qs[:100] # Default limit return qs # Custom query with business logic @strawberry_django.field def featured_fruits(self) -> list[Fruit]: return models.Fruit.objects.filter(is_featured=True, available=True).order_by( "-created_at" )[:10] # Enable Query Optimizer schema = strawberry.Schema( query=Query, extensions=[ DjangoOptimizerExtension(), ], ) ``` ```graphql query { # Get single fruit fruit(pk: "1") { id name price } # List with filters and ordering fruits( filters: { name: { iContains: "berry" } } order: { price: DESC } pagination: { offset: 0, limit: 10 } ) { id name price } # Custom query featuredFruits { id name } } ``` -------------------------------- ### HasRetvalPerm with multiple permissions Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/docs/integrations/guardian.md Example of using HasRetvalPerm with a list of permissions and any_perm=False, requiring the user to have both permissions. ```python @strawberry_django.field( extensions=[ HasRetvalPerm( ["documents.view_document", "documents.edit_document"], any_perm=False, # User must have BOTH permissions ) ] ) def sensitive_document(self, id: strawberry.ID) -> DocumentType: return models.Document.objects.get(pk=id) ``` -------------------------------- ### GOOD: Specifying Optimization Hints Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/examples/ecommerce_app/README.md Good example: specifying only the required fields with only=["first_name", "last_name"] prevents N+1 queries and deferred attribute errors. ```python # GOOD - Specifies required fields @model_property(only=["first_name", "last_name"]) def full_name(self) -> str: return f"{self.first_name} {self.last_name}" ``` -------------------------------- ### BAD: Forgetting Optimization Hints Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/examples/ecommerce_app/README.md Bad example: forgetting to specify optimization hints causes N+1 queries and a deferred attribute error. Avoid this pattern. ```python # BAD - Will cause N+1 queries @model_property def full_name(self) -> str: return f"{self.first_name} {self.last_name}" # Deferred attribute error! ``` -------------------------------- ### GOOD: Using transaction.atomic Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/examples/ecommerce_app/README.md Good example: using @transaction.atomic ensures all-or-nothing behavior for multi-step operations, preventing partial data on failure. ```python # GOOD - Atomic operation @transaction.atomic def checkout(self, user): order = Order.objects.create(user=user, cart=self) for item in self.items.all(): order.items.create(...) # All-or-nothing ``` -------------------------------- ### Configure ASGI application for subscriptions Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/docs/guide/subscriptions.md Replace the contents of MyProject.asgi.py with this to enable WebSocket support via Django Channels. It creates the Django ASGI application, imports your Strawberry schema, and wraps both with AuthGraphQLProtocolTypeRouter. Remember to change the project name and schema import path to match your setup. ```python # MyProject.asgi.py import os from django.core.asgi import get_asgi_application from strawberry_django.routers import AuthGraphQLProtocolTypeRouter os.environ.setdefault( "DJANGO_SETTINGS_MODULE", "MyProject.settings" ) # CHANGE the project name django_asgi_app = get_asgi_application() # Import your Strawberry schema after creating the django ASGI application # This ensures django.setup() has been called before any ORM models are imported # for the schema. from .schema import schema # CHANGE path to where you housed your schema file. application = AuthGraphQLProtocolTypeRouter( schema, django_application=django_asgi_app, ) ``` -------------------------------- ### Query a product by global ID Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/examples/ecommerce_app/README.md Example GraphQL query that fetches a product by its global ID (base64-encoded). ```graphql query { product(id: "UHJvZHVjdFR5cGU6MQ==") { name price } } ``` -------------------------------- ### Basic permission extensions example (types.py) Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/docs/guide/permissions.md Shows how to apply IsAuthenticated, HasPerm, and HasRetvalPerm extensions to fields. Requires importing from strawberry_django.permissions. The HasPerm extension checks the user's permission, while HasRetvalPerm checks permission on the resolved value. ```python import strawberry_django from strawberry_django.permissions import ( IsAuthenticated, HasPerm, HasSourcePerm, HasRetvalPerm, ) @strawberry_django.type class SomeType: login_required_field: RetType = strawberry_django.field( # will check if the user is authenticated extensions=[IsAuthenticated()], ) perm_required_field: OtherType = strawberry_django.field( # will check if the user has `"some_app.some_perm"` permission extensions=[HasPerm("some_app.some_perm")], ) obj_perm_required_field: OtherType = strawberry_django.field( # will check the permission for the resolved value extensions=[HasRetvalPerm("some_app.some_perm")], ) ``` -------------------------------- ### TestClient (Sync) Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/docs/guide/unit-testing.md Documentation for the synchronous TestClient class, including constructor, query method, response object, and usage examples for testing GraphQL queries, mutations, authentication, headers, file uploads, and error handling. ```APIDOC ## TestClient (Sync) ### Description Synchronous test client for testing regular Django views with GraphQL queries and mutations. ### Constructor ```python TestClient(path: str, client: Client | None = None) ``` #### Parameters - **path** (str) - Required - The URL path to your GraphQL endpoint (e.g., `"/graphql"`) - **client** (Client | None) - Optional - Django test `Client` instance. If not provided, a new one is created. ### query() Method ```python client.query( query: str, variables: dict[str, Any] | None = None, headers: dict[str, object] | None = None, files: dict[str, object] | None = None, assert_no_errors: bool = True, ) -> Response ``` #### Parameters - **query** (str) - Required - The GraphQL query/mutation string - **variables** (dict) - Optional - Variables to pass to the query - **headers** (dict) - Optional - HTTP headers to include in the request - **files** (dict) - Optional - Files for multipart uploads - **assert_no_errors** (bool) - Optional - Automatically assert no errors in response ### Response Object The `query()` method returns a `Response` object: ```python @dataclass class Response: errors: list[GraphQLFormattedError] | None data: dict[str, object] | None extensions: dict[str, object] | None ``` ### Usage Examples #### Basic Query ```python from strawberry_django.test.client import TestClient def test_query(db): client = TestClient("/graphql") response = client.query(""" query { fruits { id name } } """) assert response.errors is None assert response.data == {"fruits": [{"id": "1", "name": "Apple"}]} ``` #### Testing with Variables ```python def test_with_variables(db): client = TestClient("/graphql") response = client.query( """ query GetFruit($id: ID!) { fruit(id: $id) { name } } """, variables={"id": "1"}, ) assert response.data == {"fruit": {"name": "Apple"}} ``` #### Testing Mutations ```python def test_create_fruit(db): client = TestClient("/graphql") response = client.query( """ mutation CreateFruit($input: FruitInput!) { createFruit(input: $input) { id name } } """, variables={"input": {"name": "Banana", "color": "yellow"}}, ) assert response.errors is None assert response.data["createFruit"]["name"] == "Banana" ``` #### Testing with Authentication Use the `login()` context manager to simulate an authenticated user: ```python from django.contrib.auth import get_user_model User = get_user_model() def test_authenticated_query(db): user = User.objects.create_user(username="testuser", password="testpass") client = TestClient("/graphql") with client.login(user): response = client.query(""" query { me { username } } """) assert response.errors is None assert response.data == {"me": {"username": "testuser"}} ``` #### Testing with Custom Headers ```python def test_with_headers(db): client = TestClient("/graphql") response = client.query( """ query { protectedData } """, headers={"Authorization": "Bearer token123"}, ) assert response.errors is None ``` #### Testing File Uploads ```python from django.core.files.uploadedfile import SimpleUploadedFile def test_file_upload(db): client = TestClient("/graphql") test_file = SimpleUploadedFile( "test.txt", b"file content", content_type="text/plain" ) response = client.query( """ mutation UploadFile($file: Upload!) { uploadFile(file: $file) { success } } """, variables={"file": None}, files={"file": test_file}, ) assert response.errors is None ``` #### Expecting Errors When testing error cases, set `assert_no_errors=False`: ```python def test_validation_error(db): client = TestClient("/graphql") response = client.query( """ mutation { createFruit(input: {name: ""}) { id } } """, assert_no_errors=False, ) assert response.errors is not None assert "name" in response.errors[0]["message"].lower() ``` ``` -------------------------------- ### Query optimizer example Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/examples/ecommerce_app/README.md Shows a GraphQL query that the DjangoOptimizerExtension automatically optimizes. The optimizer selects only needed fields, joins related tables, and avoids N+1 queries. ```graphql # This query query { products(pagination: { limit: 10 }) { name brand { name } formattedPrice } } # Automatically generates optimal SQL with: # - SELECT only needed fields (name, price for formattedPrice, brand_id) # - JOIN brand table (select_related) # - No N+1 queries ``` -------------------------------- ### Run tests with pytest Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/examples/ecommerce_app/README.md Run the test suite for the Strawberry Django example app. The first command runs all tests with pytest, and the second adds coverage reporting for the app package. ```bash poetry run pytest tests/ poetry run pytest --cov=app tests/ ``` -------------------------------- ### Generated GraphQL schema with descriptions Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/docs/index.md Example schema generated when the settings above are enabled. Shows enum, type, and field descriptions derived from model docstrings and help text. ```graphql enum FruitCategory { CITRUS BERRY } """ A tasty treat """ type Fruit { id: ID! name: String! category: FruitCategory! color: Color } type Color { id: ID! """ field description """ name: String! fruits: [Fruit!] } type Query { fruits: [Fruit!]! } ``` -------------------------------- ### GOOD: Capturing by Value with Default Argument Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/examples/ecommerce_app/README.md Good example: capturing by value with a default argument ensures the callback uses the correct value even if cart.pk changes later. ```python # GOOD - Capture by value with default argument transaction.on_commit( lambda pk=cart.pk: info.context.request.session.update({"cart_pk": pk}) ) ``` -------------------------------- ### Query Optimizer: DjangoOptimizerExtension setup Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/docs/guide/performance.md Adds the DjangoOptimizerExtension to the Strawberry schema. This automatically applies select_related, prefetch_related, and only() to optimize queries, reducing the N+1 problem to 2 queries (1 for books + 1 for authors). ```python import strawberry from strawberry_django.optimizer import DjangoOptimizerExtension schema = strawberry.Schema( query=Query, extensions=[ DjangoOptimizerExtension(), # Automatically optimizes queries ], ) ``` -------------------------------- ### Generated GraphQL schema for custom resolver Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/docs/guide/pagination.md Shows the GraphQL schema produced by the custom resolver example. Includes Fruit with price, FruitOrder, PaginationInfo, FruitOffsetPaginated, OffsetPaginationInput, and the Query type with onlyAvailable and order arguments. ```graphql type Fruit { name: String! price: Decimal! } type FruitOrder { name: Ordering price: Ordering } type PaginationInfo { limit: Int! offset: Int! } type FruitOffsetPaginated { pageInfo: PaginationInfo! totalCount: Int! results: [Fruit]! } input OffsetPaginationInput { offset: Int! = 0 limit: Int = null } type Query { fruits( onlyAvailable: Boolean! = true pagination: OffsetPaginationInput order: FruitOrder ): [FruitOffsetPaginated!]! } ``` -------------------------------- ### Generated GraphQL schema for OffsetPaginated Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/docs/guide/pagination.md Shows the GraphQL schema produced by the OffsetPaginated example. Includes Fruit, PaginationInfo, FruitOffsetPaginated, OffsetPaginationInput, and the Query type with the fruits field. ```graphql type Fruit { name: String! } type PaginationInfo { limit: Int = null offset: Int! } type FruitOffsetPaginated { pageInfo: PaginationInfo! totalCount: Int! results: [Fruit]! } input OffsetPaginationInput { offset: Int! = 0 limit: Int = null } type Query { fruits(pagination: OffsetPaginationInput): [FruitOffsetPaginated!]! } ``` -------------------------------- ### Test Client Authentication with Login Context Manager Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/docs/guide/troubleshooting.md Use the login context manager from strawberry_django.test.client to persist authentication in tests. The example shows querying a 'me' field after logging in. ```python from strawberry_django.test.client import TestClient def test_authenticated_query(db): user = User.objects.create_user(username="test") client = TestClient("/graphql") with client.login(user): # ✅ Use context manager res = client.query(""" query { me { username } } """) assert res.data["me"]["username"] == "test" ``` -------------------------------- ### Populate sample data with manage.py populate_db Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/examples/ecommerce_app/README.md Creates admin user (admin/admin), test user (testuser/test123), and sample brands/products. ```shell poetry run python manage.py populate_db ``` -------------------------------- ### GraphQL query to fetch fruits with color Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/README.md Example GraphQL query to test the API at http://localhost:8000/graphql/. It fetches fruit id, name, and nested color name. ```graphql query { fruits { id name color { name } } } ``` -------------------------------- ### Configure STRAWBERRY_DJANGO settings in settings.py Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/docs/guide/settings.md Add this dictionary to your Django settings.py file to configure the strawberry-django library. Each key is optional and has a documented default; this example enables several features and customizes mutation argument names, error handling, enum generation, global ID mapping, primary key field, pagination limits, and mutation filtering. ```python STRAWBERRY_DJANGO = { "FIELD_DESCRIPTION_FROM_HELP_TEXT": True, "TYPE_DESCRIPTION_FROM_MODEL_DOCSTRING": True, "MUTATIONS_DEFAULT_ARGUMENT_NAME": "input", "MUTATIONS_DEFAULT_HANDLE_ERRORS": True, "GENERATE_ENUMS_FROM_CHOICES": False, "MAP_AUTO_ID_AS_GLOBAL_ID": True, "DEFAULT_PK_FIELD_NAME": "id", "PAGINATION_DEFAULT_LIMIT": 250, "PAGINATION_MAX_LIMIT": 1000, "ALLOW_MUTATIONS_WITHOUT_FILTERS": True, } ``` -------------------------------- ### Slow vs Fast Aggregation with annotate Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/docs/guide/performance.md This example contrasts a slow Python-level counting loop (N queries) with a fast database-level aggregation using `annotate` and `Count`. Use the annotated version to avoid N+1 queries when aggregating data. ```python from django.db.models import Count # ❌ Slow: N queries for author in Author.objects.all(): book_count = author.books.count() # ✅ Fast: Single query with annotation authors = Author.objects.annotate(book_count=Count("books")) ``` -------------------------------- ### Why prefix? - nested ordering example Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/docs/guide/legacy-ordering.md Illustrates the importance of the prefix argument in nested ordering. Without applying prefix, the custom name order would sort Fruit instead of Color. The GraphQL query shows the intended usage. ```python @strawberry_django.order(models.Fruit) class FruitOrder: name: auto color: ColorOrder | None @strawberry_django.order(models.Color) class ColorOrder: @strawberry_django.order_field def name(self, value: bool, prefix: str): # prefix is "fruit_set__" if unused root object is ordered instead if value: return ["name"] return [] ``` ```graphql { fruits( order: {color: name: ASC} ) { ... } } ``` -------------------------------- ### Django models and Strawberry types for optimizer example Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/docs/guide/optimizer.md Defines the Django models and corresponding Strawberry types used to demonstrate the optimizer. The models define Artist, Album, and Song with relationships; the types use strawberry_django.type and auto fields, including an annotated field albums_count. ```python class Artist(models.Model): name = models.CharField() class Album(models.Model): name = models.CharField() release_date = models.DateTimeField() artist = models.ForeignKey("Artist", related_name="albums") class Song(models.Model): name = model.CharField() duration = models.DecimalField() album = models.ForeignKey("Album", related_name="songs") ``` ```python from strawberry import auto import strawberry_django @strawberry_django.type(Artist) class ArtistType: name: auto albums: list["AlbumType"] albums_count: int = strawberry_django.field(annotate=Count("albums")) @strawberry_django.type(Album) class AlbumType: name: auto release_date: auto artist: ArtistType songs: list["SongType"] @strawberry_django.type(Song) class SongType: name: auto duration: auto album_type: AlbumType @strawberry.type class Query: artist: Artist = strawberry_django.field() songs: list[SongType] = strawberry_django.field() ``` -------------------------------- ### Query single object by primary key and all objects Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/docs/guide/queries.md Example GraphQL query showing how to fetch a single object by primary key using the `pk` argument and how to fetch all objects. The `fruit` query automatically provides a primary key filter, while `fruits` returns all objects by default. ```graphql query { # Single object by primary key fruit(pk: "1") { id name } # All objects fruits { id name } } ``` -------------------------------- ### Testing with authentication using login() context manager Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/docs/guide/unit-testing.md Shows how to simulate an authenticated user by using the login() context manager on the TestClient. ```python from django.contrib.auth import get_user_model User = get_user_model() def test_authenticated_query(db): user = User.objects.create_user(username="testuser", password="testpass") client = TestClient("/graphql") with client.login(user): response = client.query(""" query { me { username } } """) assert response.errors is None assert response.data == {"me": {"username": "testuser"}} ``` -------------------------------- ### Run the ASGI development server Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/docs/guide/subscriptions.md Run the development server with ASGI support. This command now uses Daphne to serve WebSocket connections. ```bash ./manage.py runserver ``` -------------------------------- ### Run Production ASGI Server with Daphne, Uvicorn, or Hypercorn Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/docs/integrations/channels.md Run the server in production using an ASGI server. Three alternatives are shown: Daphne, Uvicorn, and Hypercorn. ```bash # Daphne daphne myproject.asgi:application # Uvicorn uvicorn myproject.asgi:application --host 0.0.0.0 --port 8000 # Hypercorn hypercorn myproject.asgi:application --bind 0.0.0.0:8000 ``` -------------------------------- ### Update INSTALLED_APPS in settings.py Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/docs/integrations/channels.md Add 'daphne' and 'channels' to INSTALLED_APPS. 'daphne' must be before 'staticfiles' to override runserver. ```python INSTALLED_APPS = [ "daphne", # Must be before staticfiles for runserver override "django.contrib.staticfiles", # ... other apps "channels", "strawberry_django", ] ``` -------------------------------- ### Run guardian migrations Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/docs/integrations/guardian.md Run migrations to create guardian's permission tables. ```bash python manage.py migrate guardian ``` -------------------------------- ### HasRetvalPerm with superuser bypass Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/docs/integrations/guardian.md Example of using HasRetvalPerm with with_superuser=True, allowing superusers to access without the specific permission. ```python @strawberry_django.field( extensions=[ HasRetvalPerm( "documents.view_document", with_superuser=True, # Superusers can access without the specific permission ) ] ) def document(self, id: strawberry.ID) -> DocumentType: return models.Document.objects.get(pk=id) ``` -------------------------------- ### Query with pagination argument Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/docs/guide/pagination.md Example GraphQL query using the pagination argument to request a limited number of fruits. ```graphql query { fruits(pagination: { offset: 0, limit: 2 }) { name } } ``` -------------------------------- ### Run migrations with manage.py migrate Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/examples/ecommerce_app/README.md Applies database migrations. ```shell poetry run python manage.py migrate ``` -------------------------------- ### BAD: Sync Code in Async Resolver Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/examples/ecommerce_app/README.md Bad example: using sync code in an async resolver can cause SynchronousOnlyOperation. Avoid this pattern. ```python # BAD - Sync code in async resolver async def my_resolver(self, info: Info): user = info.context.request.user # Might cause SynchronousOnlyOperation ``` -------------------------------- ### Make migrations and migrate Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/docs/index.md Run Django's makemigrations and migrate commands to create the database schema for the defined models. ```sh python manage.py makemigrations python manage.py migrate ``` -------------------------------- ### Basic usage of AuthGraphQLProtocolTypeRouter Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/docs/integrations/channels.md Sets up the router with a schema and optional Django ASGI app. The url_pattern defaults to '^graphql'. It automatically adds AuthMiddlewareStack and AllowedHostsOriginValidator. ```python from strawberry_django.routers import AuthGraphQLProtocolTypeRouter application = AuthGraphQLProtocolTypeRouter( schema, # Your Strawberry schema django_application=django_asgi, # Optional: Django ASGI app for non-GraphQL routes url_pattern="^graphql", # Optional: URL pattern (default: "^graphql") ) ``` -------------------------------- ### GraphQL query using list-based AND filter Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/docs/guide/filters.md Example query that uses the list-based AND filter to find vegetables whose names contain both 'blue' and 'squash'. ```graphql { vegetables( filters: { AND: [{ name: { contains: "blue" } }, { name: { contains: "squash" } }] } ) { id } } ``` -------------------------------- ### How It Works: Models and GraphQL Query Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/docs/guide/performance.md Shows the Django models and the GraphQL query used to demonstrate the optimizer's behavior. ```python # models.py class Publisher(models.Model): name = models.CharField(max_length=100) class Author(models.Model): name = models.CharField(max_length=100) publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE) class Book(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey(Author, on_delete=models.CASCADE) isbn = models.CharField(max_length=13) ``` ```graphql query { books { title isbn author { name publisher { name } } } } ``` -------------------------------- ### Query OffsetPaginated fruits Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/docs/guide/pagination.md Example GraphQL query to fetch paginated fruits with totalCount, pageInfo, and results. Uses the pagination argument with offset and limit. ```graphql query { fruits(pagination: { offset: 0, limit: 2 }) { totalCount pageInfo { limit offset } results { name } } } ``` -------------------------------- ### AsyncTestClient async login test Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/docs/guide/unit-testing.md Demonstrates async login with AsyncTestClient. Uses `sync_to_async` to create a user, then logs in with `client.login(user)` in an async context. The query is executed within the login context and the response data is asserted. ```python @pytest.mark.asyncio async def test_async_authenticated(db): user = await sync_to_async(User.objects.create_user)( username="testuser", password="testpass" ) client = AsyncTestClient("/graphql") async with client.login(user): response = await client.query(""" query { me { username } } """) assert response.data == {"me": {"username": "testuser"}} ``` -------------------------------- ### Relay-style cursor pagination with DjangoListConnection Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/docs/guide/queries.md Sets up a Relay-style cursor connection using DjangoListConnection and queries it with first and after arguments to get edges, cursors, and pageInfo. ```python from strawberry_django.relay import DjangoListConnection import strawberry_django @strawberry.type class Query: fruits: DjangoListConnection[Fruit] = strawberry_django.connection() ``` ```graphql query { fruits(first: 10, after: "cursor") { edges { node { id name } cursor } pageInfo { hasNextPage endCursor } } } ``` -------------------------------- ### BAD: Capturing Variable by Reference in Lambda Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/examples/ecommerce_app/README.md Bad example: capturing variables by reference in a lambda can cause the callback to use a changed value. Avoid this pattern. ```python # BAD - cart.pk might change before callback runs transaction.on_commit(lambda: info.context.request.session.update({"cart_pk": cart.pk})) ``` -------------------------------- ### Test validation with test client Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/docs/guide/validation.md Test validation using the test client. The example sends a mutation with invalid data and asserts that the response contains messages. ```python def test_validation(db): client = TestClient("/graphql") res = client.query(""" mutation { createUser(data: { email: "invalid", age: 15 }) { ... on OperationInfo { messages { field message } } } } """) assert res.data["createUser"]["messages"] ``` -------------------------------- ### Initialize Django before importing schema in asgi.py Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/docs/faq.md Fix 'AppRegistryNotReady' by calling get_asgi_application() before importing the schema that imports models. ```python import os from django.core.asgi import get_asgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings") # Initialize Django FIRST django_asgi_app = get_asgi_application() # THEN import your schema (which imports models) from myproject.schema import schema ``` -------------------------------- ### GraphQL query using AND/OR filters Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/docs/guide/filters.md Example query that filters fruits by name 'kebab' or name 'raspberry' using the OR field. Demonstrates complex filtering with AND, OR, NOT, and DISTINCT. ```graphql { fruits( filters: { name: "kebab" OR: { name: "raspberry" } } ) { ... } } ``` -------------------------------- ### Create a Federated Schema with strawberry.federation.Schema Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/docs/integrations/federation.md Creates a federated schema using strawberry.federation.Schema instead of the regular strawberry.Schema, with a query that returns all products. ```python from strawberry.federation import Schema @strawberry.type class Query: @strawberry_django.field def products(self) -> list[Product]: return models.Product.objects.all() schema = Schema(query=Query) ``` -------------------------------- ### BAD: No Atomicity in Multi-step Operation Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/examples/ecommerce_app/README.md Bad example: not using transactions for multi-step operations. If an item creation fails, the order still exists, leaving inconsistent data. ```python # BAD - No atomicity def checkout(self, user): order = Order.objects.create(user=user, cart=self) for item in self.items.all(): order.items.create(...) # If this fails, order still exists! ``` -------------------------------- ### Serve GraphQL with AsyncGraphQLView in urls.py Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/docs/index.md Add the GraphQL endpoint to your URL configuration using AsyncGraphQLView. Requires importing the schema from your project's schema module. ```python from django.urls import include, path from strawberry.django.views import AsyncGraphQLView from .schema import schema urlpatterns = [ path("graphql", AsyncGraphQLView.as_view(schema=schema)), ] ``` -------------------------------- ### Handle Django errors with handle_django_errors Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/docs/index.md Use handle_django_errors=True in mutations.create to automatically return structured errors. The example shows a create_fruit mutation and the corresponding error response format. ```python @strawberry.type class Mutation: create_fruit: Fruit = mutations.create( FruitInput, handle_django_errors=True, # Automatically returns structured errors ) ``` ```json { "data": { "createFruit": { "__typename": "OperationInfo", "messages": [ { "field": "name", "message": "This field is required", "kind": "VALIDATION" } ] } } } ``` -------------------------------- ### Database Aggregations in Resolvers Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/docs/guide/performance.md Use database aggregations in GraphQL resolvers. The example annotates an Author type with book_count and avg_rating using Django's Count and Avg. ```python from django.db.models import Count, Avg @strawberry_django.type(models.Author) class Author: name: auto book_count: int = strawberry_django.field(annotate={"book_count": Count("books")}) avg_rating: float = strawberry_django.field( annotate={"avg_rating": Avg("books__rating")} ) ``` -------------------------------- ### Configure default and maximum pagination limits (settings.py) Source: https://github.com/strawberry-graphql/strawberry-django/blob/main/docs/guide/pagination.md Shows how to set PAGINATION_DEFAULT_LIMIT and PAGINATION_MAX_LIMIT in the STRAWBERRY_DJANGO settings to control pagination behavior. ```python STRAWBERRY_DJANGO = { "PAGINATION_DEFAULT_LIMIT": 100, "PAGINATION_MAX_LIMIT": 100, # Cap all pagination requests at 100 records } ```