strawberry-graphql / strawberry-django

Strawberry GraphQL Django extension
https://strawberry.rocks/docs/django
MIT License
416 stars 121 forks source link

Way to split up query across django apps #284

Closed TWeidi closed 1 year ago

TWeidi commented 1 year ago

Rather a question than an issue: Is there a way to split up the Query object across different django apps and create the central Query by inheriting from the app-specific ones in a similar fashion as it is possible in graphene-django? Something like:

# schema.py
import strawberry

from fruits.types import Query as FruitQueries
from vegetables.types import Query as VegetableQueries

@strawberry.type
class Query(FruitQueries, VegetableQueries):
    """All available queries for this schema."""
    ...
    # will include 'fruits' from FruitsQueries and 'vegetables' from VegetableQueries

schema = strawberry.Schema(
    query=Query,
)

with

# fruits.types.py
import strawberry
import strawberry_django

from . import models

@strawberry_django.type(models.Fruit)
class Fruit:
    name: str
    color: str

@strawberry.type
class Query:
    fruits: list[Fruit] = strawberry.django.field()

and

# vegetables.types.py
import strawberry
import strawberry_django

from . import models

@strawberry_django.type(models.Vegetable)
class Vegetable:
    name: str
    color: str

@strawberry.type
class Query:
    vegetables: list[Vegetable] = strawberry.django.field()

Upvote & Fund

Fund with Polar

bellini666 commented 1 year ago

Hey @TWeidi ,

You can use merge_types for that!

Instead of:

@strawberry.type
class Query(FruitQueries, VegetableQueries):
    """All available queries for this schema."""
    ...

You do:

Query = merge_types(Query, (FruitsQueries, VegetableQueries))
TWeidi commented 1 year ago

Good morning!

Thank you for the hint. Admittedly, I have completely missed out that part of the docs. Just tried the merge_types function in my schema but unfortunately I do get a metaclass conflict. Maybe that's related to one of my Django model Mixins which I'm using across my apps. I've prepared a separate branch in my repo that exhibit the issue. Maybe you can have a look at it on occasion.

TWeidi commented 1 year ago

OK, you can ignore my last comment, i found the cause of the issue. I was mixing up "type" declared in strawberry with "type" declared in strawberry-django. When defining a Query object it is essential to use the "strawberry.type" as decorator and not the "strawberry_django.type".

bellini666 commented 1 year ago

Awesome! :)

Well, considering that this should be resolved, I'm closing this issue.