3

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!

  • Is providing more fields than necessary okay? The beauty of GraphQL is that the client can request only the fields they want – Zain Patel Jun 29 '20 at 15:46
  • This is the way forward, one you use for Public APIs and one for Private APIs, yep, the other way is to resolve each field individually and check if user has permission for it, but you don't want to go through that route. This will more than suffice. – frozenOne Jun 29 '20 at 16:21
  • @frozenOne Yes, but the question is how to explicitly specify which field to use. It's very concerning that graphene_django just automatically selects one. I can't accept the risk associated with not having these explicitly defined. Am digging through the graphene_django code now to see what I can learn. – Kevin Dice Feb 25 '21 at 18:39
  • I created a more specific question similar to this at https://stackoverflow.com/questions/70826464/graphene-django-determine-object-type-when-multiple-graphql-object-types-use, but press having multiple object types for the same model being a _fixed decision_. I believe this is in the confines of what graphql is designed to do. graphene-django, despite being sent a typed relay ID, returns other object types if they match the django model. – tony Jan 23 '22 at 20:53

1 Answers1

0

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.