Strawberry GraphQL Django Integration

0.82.1 · active · verified Sat Apr 11

Strawberry GraphQL Django integration provides powerful tools to build GraphQL APIs with Django. It automatically generates GraphQL types, queries, mutations, and resolvers from your Django models with full type safety. The library is actively maintained, currently at version 0.82.1, and supports Django 4.2-6.0 and Python 3.10-3.14, with regular updates.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define Django models, create corresponding Strawberry GraphQL types using `strawberry_django.type` and `auto`, and then expose them via a GraphQL `Query` field. It also shows the integration of `DjangoOptimizerExtension` for performance and how to set up the Django URLconf to serve the GraphQL API. The example defines simple Fruit and Color models with a foreign key relationship.

import strawberry
import strawberry_django
from django.db import models
from strawberry.django.views import AsyncGraphQLView
from strawberry_django.optimizer import DjangoOptimizerExtension

# models.py (excerpt)
class Color(models.Model):
    name = models.CharField(max_length=20)

    def __str__(self):
        return self.name

class Fruit(models.Model):
    name = models.CharField(max_length=20)
    color = models.ForeignKey(Color, on_delete=models.CASCADE, related_name="fruits")

    def __str__(self):
        return self.name

# types.py (excerpt, often in app.types.py)
@strawberry_django.type(Color)
class ColorType:
    id: strawberry.ID
    name: str
    fruits: list['FruitType'] # Forward reference

@strawberry_django.type(Fruit)
class FruitType:
    id: strawberry.ID
    name: str
    color: ColorType

# schema.py (excerpt, often in project.schema.py)
@strawberry.type
class Query:
    @strawberry_django.field
    def fruits(self) -> list[FruitType]:
        return Fruit.objects.all()

    @strawberry_django.field
    def colors(self) -> list[ColorType]:
        return Color.objects.all()

schema = strawberry.Schema(
    query=Query,
    extensions=[
        DjangoOptimizerExtension, # Recommended for N+1 query optimization
    ]
)

# urls.py (excerpt)
# from django.urls import path
# from myproject.schema import schema # Assuming schema defined in myproject/schema.py
# from strawberry.django.views import AsyncGraphQLView
#
# urlpatterns = [
#     path("graphql/", AsyncGraphQLView.as_view(schema=schema)),
# ]

# To run this example, you'd typically set up a Django project:
# 1. Create a Django project and app.
# 2. Add 'strawberry.django' and your app to INSTALLED_APPS in settings.py.
# 3. Define models (Color, Fruit) in your app's models.py.
# 4. Define types (ColorType, FruitType) in your app's types.py.
# 5. Define Query and Schema in your project's schema.py.
# 6. Add the GraphQL endpoint to your project's urls.py.

view raw JSON →