Is there a way to get graphene to work with django GenericRelation field?

放肆的年华 提交于 2019-12-11 19:11:59

问题


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.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')
    file = models.FileField(upload_to=user_directory_path)
class Aparto(models.Model):
    agency = models.CharField(max_length=100, default='Default')
    features = models.TextField()
    attachments = GenericRelation(Attachment)

graphene classes:

class ApartoType(DjangoObjectType):
    class Meta:
        model = Aparto
class Query(graphene.ObjectType):
    all  = graphene.List(ApartoType)
    def resolve_all(self, info, **kwargs):
        return Aparto.objects.all()

schema = graphene.Schema(query=Query)

I expect the attachments field to appear in the graphql queries results. Only agency and features are showing.


回答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:

class AttachmentType(DjangoObjectType):
    class Meta:
        model = Attachment

class ApartoType(DjangoObjectType):
    class Meta:
        model = Aparto

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


来源:https://stackoverflow.com/questions/56146966/is-there-a-way-to-get-graphene-to-work-with-django-genericrelation-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!