python - 如何使用 django_graphene 解析 django 模型的自定义字段?

标签 python django graphql graphene-python

查看 graphene_django,我看到他们有一堆解析器拾取 django 模型字段,将它们映射到 Graphite 烯类型。

我有一个 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 方法)

我在没有深入了解 Graphite 烯类型和 django 模型字段类型之间的映射中发生了什么的情况下就弄明白了。

基于此: https://docs.graphene-python.org/en/latest/types/objecttypes/#resolvers

相同的函数名称,但参数化不同。

关于python - 如何使用 django_graphene 解析 django 模型的自定义字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52767366/

相关文章:

reactjs - 如何在 Redux-toolkit rtk-query graphql 应用程序中处理错误格式

react-native - React-native Android 应用程序发布版本上的 Graphql 网络错误

python - 自动简化冗余算术关系

python - 带有 if else hasattr 的 for 循环中的字典列表

python - 当 scipy.integrate.odeint 中输出达到 0 时停止积分

python - 在 Django 中使用案例

python - Django 自动完成选择在部署时不起作用

python - 使用 Django 对 SQLite 执行原始 SQL 结果为 `DatabaseError: near "?": syntax error`

python - 为什么在 Django 中重写 Model.save() 函数不起作用?

javascript - 无法处理 React ApolloClient 中的错误