将JSON模型字段与Django石墨烯一起使用 [英] Using json model field with django graphene

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

问题描述

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

I'm working with graphql endpoint for my project. One of models has textfield which contains some json. If i request list of my entities via graphql, I'm getting this json like a string. How to reach ability to use it in graphql as nested structure with ability of filtering, choosing some properties etc.

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

推荐答案

您可以使用自定义类型(例如,

You can declare resolver for data field with a custom type, e.g.

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

You might be able to extend this idea for DataType data to return DataType data, and thus be able to handle arbitrarily deep trees of data.

这篇关于将JSON模型字段与Django石墨烯一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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