Han*_*rus 5 python django graphql graphene-python
看看 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 = ???
Run Code Online (Sandbox Code Playgroud)
我知道我可以为查询编写一个单独的字段和解析器对,但我更希望将其作为该模型架构的一部分。
我意识到我可以做什么:
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()
Run Code Online (Sandbox Code Playgroud)
但是——这意味着一个单独的往返,获取 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())
Run Code Online (Sandbox Code Playgroud)
(custom_field有一个to_json方法)
我在没有深入弄清楚石墨烯类型和 django 模型字段类型之间的映射中发生了什么的情况下就弄清楚了。
它基于此: https://docs.graphene-python.org/en/latest/types/objecttypes/#resolvers
函数名称相同,但参数化不同。
| 归档时间: |
|
| 查看次数: |
4461 次 |
| 最近记录: |