Django-graphene multiple types for the same model

Viewed 696

I have a quite big graphene-django API which feeds two applications.

My first approach to restrict access to some fields was to have multiple DjangoObjectTypes for the same model, and use fields to limit which fields can be accessed on each type.

Example for Organization:

class OrganizationType(DjangoObjectType):
    class Meta:
        model = Organization
        fields = (
            "id",
            "name",
            "members"
            "date_created",
            "last_modified",
        )
class LiteOrganizationType(DjangoObjectType):
    class Meta:
        model = Organization
        fields = (
            "id",
            "name",
        )

Is this the best approach or should I have only one type and resolve fields based on the current user/app/etc..?

The main issue I have experienced is that I need to explicitly define which type to use then in other related types.

Thanks in advance!

1 Answers

for me works order the classes based on its quantity of fields, from the class with less fields to class with more fields. In your case

# First the class with less fields
class LiteOrganizationType(DjangoObjectType):
    class Meta:
        model = Organization
        fields = (
            "id",
            "name",
        )

# Last the class with more fields.
class OrganizationType(DjangoObjectType):
    class Meta:
        model = Organization
        fields = (
            "id",
            "name",
            "members"
            "date_created",
            "last_modified",
        )

And that's all.

Related