如何使用 django_graphene 解析 Django 模型的自定义字段?
How can I resolve custom fields for django models using django_graphene?
查看 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 = ???
我知道我可以为查询编写一个单独的字段和解析器对,但我更希望它作为该模型的架构的一部分可用。
我意识到我能做的:
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 架构的一部分?
好的,我可以通过以下方式让它工作:
# schema
class RecipeType(DjangoObjectType):
class Meta:
model = Recipe
custom_field = graphene.JSONString(resolver=lambda my_obj, resolve_obj: my_obj.custom_field.to_json())
(custom_field
有一个 to_json
方法)
我在没有深入了解石墨烯类型和 django 模型字段类型之间的映射中发生了什么的情况下就弄明白了。
基于此:
https://docs.graphene-python.org/en/latest/types/objecttypes/#resolvers
相同的函数名称,但参数化不同。
查看 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 = ???
我知道我可以为查询编写一个单独的字段和解析器对,但我更希望它作为该模型的架构的一部分可用。
我意识到我能做的:
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 架构的一部分?
好的,我可以通过以下方式让它工作:
# schema
class RecipeType(DjangoObjectType):
class Meta:
model = Recipe
custom_field = graphene.JSONString(resolver=lambda my_obj, resolve_obj: my_obj.custom_field.to_json())
(custom_field
有一个 to_json
方法)
我在没有深入了解石墨烯类型和 django 模型字段类型之间的映射中发生了什么的情况下就弄明白了。
基于此: https://docs.graphene-python.org/en/latest/types/objecttypes/#resolvers
相同的函数名称,但参数化不同。