且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Graphene-django 与 ManyToMany &直通表

更新时间:2023-12-01 14:44:04

您可以通过创建一个表示来自两个模型的字段的类型来实现这一点.例如:

You can achieve this by creating a type which expresses fields from both models. For example:

import graphene
from graphene_django.types import DjangoObjectType


# hybrid type, expresses some characteristics of Member and Group
class UserGroupType(DjangoObjectType):
    class Meta:
        model = Membership
    
        # date_joined is automatically derived from the membership
        # instance, name and id are declared below.
        fields = ('id', 'name', 'date_joined', )
    
    id = graphene.ID()
    name = graphene.String()
    
    def resolve_id(value_obj, info):
        return value_obj.group.pk

    def resolve_name(value_obj, info):
        return value_obj.group.name


class PersonType(DjangoObjectType):
    class Meta:
        model = Person
    
        # id and name are automatically derived from the person
        # instance, groups is declared below, overriding the 
        # normal model relationship.
        fields = ('id', 'name', 'groups', )
    
    groups = graphene.List(UserGroupType)
    
    def resolve_groups(value_obj, info):
        return value_obj.memberships

对于从 Graphene 的 ObjectType(其中 继承自 to express输出中的字段您需要两件事:

For any type built from Graphene's ObjectType (which DjangoObjectType descends from), to express a field in output you need two things:

  1. 字段的类型的声明
  2. 生成要转换为该类型的结果的解析器方法

DjangoObjectType 评估您提供的模型以自动生成这些模型并使用 fields 属性 让您自定义要显示的属性.

DjangoObjectType evaluates the model you provide it to generate these automatically and uses the fields attribute to let you customize what properties to reveal.

通过自定义fields,然后为您想要添加的内容添加手动道具/解析器,您可以使类型返回您想要的任何内容.

By customizing fields and then adding manual props/resolvers for what you want to add you can make the type return anything you want.

请注意,解析器不会接收 self 作为第一个参数,而是获得 值对象.值对象是查询解析器的返回值,通常是模型的实例或与过滤器匹配的模型数组等.

Note the resolvers don't receive self as the first argument, but instead get a value object. The value object is the return value of your query resolver and is generally an instance of your model or an array of models that matched a filter, etc.