在Django石墨烯中使用JSON模型字段

时间:2018-06-27 14:18:18

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

我正在为我的项目使用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

1 个答案:

答案 0 :(得分:0)

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

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数据,从而能够处理任意深度的数据树。