【问题标题】:Using json model field with django graphene将 json 模型字段与 django 石墨烯一起使用
【发布时间】:2018-12-06 11:46:56
【问题描述】:

我正在为我的项目使用 graphql 端点。其中一个模型具有包含一些 json 的文本字段。如果我通过 graphql 请求我的实体列表,我会像字符串一样得到这个 json。如何在 graphql 中将其作为嵌套结构使用,并具有过滤、选择某些属性等能力。

class SysObjects(models.Model):
    id = models.BigAutoField(primary_key=True)
    user_id = models.BigIntegerField()
    type_id = models.PositiveIntegerField(blank=True, null=True)
    # status = models.ForeignKey('SysObjectsStatuses', models.DO_NOTHING, blank=True, null=True)
    title = models.CharField(max_length=255, blank=True, null=True)
    data = models.TextField(blank=True, null=True) #json string is here
    visible = models.IntegerField()
    date_actual = models.DateTimeField()
    date_update = models.DateTimeField(blank=True, null=True)
    date_add = models.DateTimeField(blank=True, null=True)
    orig = models.CharField(max_length=255, blank=True, null=True)
    is_color = models.PositiveIntegerField()

    class Meta:
        managed = False
        db_table = 'sys_objects'
        app_label = "default"

    def __str__(self):
        return self.title

【问题讨论】:

    标签: django django-models graphql python-3.6 graphene-python


    【解决方案1】:

    您可以为具有自定义类型的数据字段声明解析器,例如

    import graphene
    from graphene.django.types import DjangoObjectType
    
    class SysObjectsType(DjangoObjectType):
        data = DataType()
    
        class Meta:
            model = SysObjects
    
        def resolve_data(self, info):
            # What you return here depends on how you are unpacking the JSON data
            return self.data
    
    class DataType(graphene.ObjectType):
        # What you put here depends on how you want to structure the JSON output
        ...
    

    您或许可以将这个想法扩展为 DataType 数据以返回 DataType 数据,从而能够处理任意深度的数据树。

    【讨论】:

      猜你喜欢
      • 2017-11-26
      • 2018-01-29
      • 2019-04-03
      • 2018-06-28
      • 2023-04-09
      • 2018-10-06
      • 2019-04-28
      • 2020-01-27
      • 2018-01-11
      相关资源
      最近更新 更多