Skip to content Skip to sidebar Skip to footer

Is There A Way To Get Graphene To Work With Django Genericrelation Field?

I have some django model generic relation fields that I want to appear in graphql queries. Does graphene support Generic types? class Attachment(models.Model): user = models.Fo

Solution 1:

You need to expose Attachment to your schema. Graphene needs a type to work with for any related fields, so they need to be exposed as well.

In addition, you're likely going to want to resolve related attachments, so you'll want to add a resolver for them.

In your graphene classes, try:

classAttachmentType(DjangoObjectType):
    classMeta:
        model = AttachmentclassApartoType(DjangoObjectType):
    classMeta:
        model = Aparto

    attachments = graphene.List(AttachmentType)
    def resolve_attachments(root, info):
        return root.attachments.all()

Solution 2:

It's not perfect, but this is how I did it: First create a proxy class (I found that abstract = True also works), this should have all the fields that all the possible Generically Related objects can have.

classCatchAll(RelatedModelYouInheritFrom):
    class Meta:
        proxy = True

Then make a type for the proxy model

classCatchAllType(DjangoObjectType):
    classMeta:
        model = CatchAllfields= ('some_var', 'other_var')

and in the resolver that returns instances of multiple classes: cast the instance as a CatchAll:

classModelWithGenericForeignKeyType(DjangoObjectType):classMeta:
        model = ModelWithGenericForeignKey
        fields = ('other_var', 'some_var')

    generic_relation = graphene.Field(CatchAllType)


    defresolve_generic_relation(self, info, **kwargs):
        d = self.generic_relation.__dict__  # turn the model in a dict
        d.pop('_state')  # remove the statereturn CatchAll(**d)  # cast the object of any class into the CatchAll

Post a Comment for "Is There A Way To Get Graphene To Work With Django Genericrelation Field?"