有没有一种方法可以使石墨烯与Django GenericRelation字段一起使用? [英] Is there a way to get graphene to work with django GenericRelation field?

查看:37
本文介绍了有没有一种方法可以使石墨烯与Django GenericRelation字段一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些要在graphql查询中显示的django模型通用关系字段.石墨烯是否支持通用类型?

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)

石墨烯类:

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)

我希望附件字段出现在graphql查询结果中.仅显示代理商和功能.

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

推荐答案

您需要向架构公开附件.石墨烯需要 type 才能用于任何相关字段,因此也需要公开.

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()

这篇关于有没有一种方法可以使石墨烯与Django GenericRelation字段一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆