graphene-django icon indicating copy to clipboard operation
graphene-django copied to clipboard

Is there a way to elegantly use a django model as an input object type?

Open rossm6 opened this issue 3 years ago • 1 comments

Say I have,

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)

Is it possible to avoid writing out PersonNodeInput? It would be nice if you could subclass something like "DjangoInputObjectType" and specify the model and fields you want in a Meta attribute.

SO question - https://stackoverflow.com/questions/66286436/is-there-a-way-to-elegantly-use-a-django-model-as-an-input-object-type

rossm6 avatar Feb 20 '21 19:02 rossm6

There isn't a class for that, it might be a good addition. graphene_django.types.construct_fields takes a model and outputs graphene fields.

zbyte64 avatar Mar 21 '21 21:03 zbyte64

In graphene-django v3.1.1 there's a new DjangoFormInputObjectType which could work for your purpose. Docs here (added in https://github.com/graphql-python/graphene-django/pull/1325).

There's also the great https://github.com/tOgg1/graphene-django-cud library which may accomplish what you need.

sjdemartini avatar Jun 11 '23 19:06 sjdemartini