【问题标题】:Is there a way to elegantly use a django model as an input object type?有没有办法优雅地使用 django 模型作为输入对象类型?
【发布时间】:2021-02-19 23:44:26
【问题描述】:

说我有,

class PersonNode(DjangoObjectType):
    class Meta:
        model = Person
        fields = ('first_name', 'last_name', 'age',
                  'sex', 'alive', 'unique_identifier',)
        filter_fields = ('first_name', 'last_name', 'age',
                         'sex', 'alive', 'unique_identifier',)
        interfaces = (graphene.relay.Node,)

class PersonNodeInput(graphene.InputObjectType):
    first_name = graphene.String()
    last_name = graphene.String()
    # rest of person model fields

class Valid(graphene.ObjectType):
    ok = graphene.Boolean()

class Query(graphene.ObjectType):
    validate_person = graphene.Field(Valid, args={
                                     "data": PersonNodeInput()})
    person = graphene.relay.Node.Field(PersonNode)
    all_people = DjangoFilterConnectionField(PersonNode)

    def resolve_validate_person(root, info, data):
        print("resolve validate person")
        return Valid(ok=True)

是否可以避免写出 PersonNodeInput?如果您可以将“DjangoInputObjectType”之类的子类化并在 Meta 属性中指定所需的模型和字段,那就太好了。

【问题讨论】:

    标签: graphene-django


    【解决方案1】:

    我们一直在使用这个 Graphene Django CUD 库,它试图删除一些涉及定义突变的样板。

    让你的案例适应他们的例子看起来像

    from graphene_django_cud.mutations import DjangoCreateMutation
    
    class CreatePersonMutation(DjangoCreateMutation):
        class Meta:
            model = Person
    
    class PersonMutations(graphene.ObjectType):
        create_person = CreateUserMutation.Field()
    
    schema = Schema(mutation=PersonMutations)
    

    我不知道它与 Relay 节点的工作情况如何,因为我们没有使用 Relay。

    【讨论】:

      猜你喜欢
      • 2011-04-07
      • 1970-01-01
      • 2012-04-14
      • 1970-01-01
      • 1970-01-01
      • 2016-03-25
      • 2023-01-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多