3

my goal: I am trying to return all the fields of the posts if the user has an id of 1, and I want to return only 3 fields if else. My problem is: in the query or mutations I can do info.context.user.id but in the schema I can't do that. Here in my following code you can noticed his undefined variable current_loggedin_user which I don't know how to get its value.

import graphene
from graphene_django import DjangoObjectType
from . import models
from django.conf import settings


class Posts(DjangoObjectType):
    class Meta:
        model = models.ExtendUser
        if (current_logedin_user.id==1):
            field = '__all_'
        else:
            fields = ['username', 'id', 'imageUrl']

Mark Chackerian
  • 21,866
  • 6
  • 108
  • 99
Ali Husham
  • 816
  • 10
  • 31

2 Answers2

3

You need to include all fields that are visible to anyone to the schema, and then customize the resolver methods for the fields that you want to hide for some users. For example:

class Posts(DjangoObjectType):
    class Meta:
        model = models.ExtendUser
    def resolve_restricted_field(self, info):
        if info.context.user.id == 1:
            return self.restricted_field
        return None

For more examples, see How to limit field access on a model based on user type on Graphene/Django?

Mark Chackerian
  • 21,866
  • 6
  • 108
  • 99
2

Try something like this

    class Posts(DjangoObjectType):
        class Meta:
            model = models.ExtendUser

    class Query(ObjectType):
        fields = graphene.List(Posts)

        def resolve_fields(self, info, **kwargs):
            if info.context.user.pk == 1:
                return ExtendUser.objects.all()

            return ExtendUser.objects.values_list('username', 'id', 'imageUrl', flat=True)
Yankz Kuyateh
  • 612
  • 1
  • 5
  • 18