【发布时间】:2019-03-16 23:12:54
【问题描述】:
查看 graphene_django,我看到他们有一堆解析器拾取 django 模型字段,将它们映射到石墨烯类型。
我有一个JSONField 的子类,我也想被接走。
:
# models
class Recipe(models.Model):
name = models.CharField(max_length=100)
instructions = models.TextField()
ingredients = models.ManyToManyField(
Ingredient, related_name='recipes'
)
custom_field = JSONFieldSubclass(....)
# schema
class RecipeType(DjangoObjectType):
class Meta:
model = Recipe
custom_field = ???
我知道我可以为 Query 编写单独的字段和解析器对,但我希望它可以作为该模型架构的一部分使用。
我意识到我能做什么:
class RecipeQuery:
custom_field = graphene.JSONString(id=graphene.ID(required=True))
def resolve_custom_field(self, info, **kwargs):
id = kwargs.get('id')
instance = get_item_by_id(id)
return instance.custom_field.to_json()
但是——这意味着一个单独的往返,获取 id 然后获取该项目的 custom_field,对吗?
有没有一种方法可以让我将其视为 RecipeType 架构的一部分?
【问题讨论】:
标签: python django graphql graphene-python