Using json model field with django graphene

帅比萌擦擦* 提交于 2021-01-27 18:04:01

问题


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

回答1:


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
    ...

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.



来源:https://stackoverflow.com/questions/51065178/using-json-model-field-with-django-graphene

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