How to hide django default filters from others except admin user?

How to hide django default filters from others except admin user?


1

I have below User graphql API endpoint in my application.

Query

class Query(UserQuery, graphene.ObjectType):
    all_users = DjangoFilterConnectionField(
        UserType, filterset_class=UserFilter)

Type

class UserType(DjangoObjectType):
    class Meta:
        model = User
        fields = "__all__"
        interfaces = (graphene.relay.Node,)

Filter

class UserFilter(FilterSet):
    user_name_search = CharFilter(
        method='user_name_filter', label='User Name Search'
    )

    class Meta:
        model = User
        fields = [
            'user_name_search',
            'user_id',
            'first_name',
            'last_name',
            'email',
            'gender',
            'height',
            'rating',
            'phone',
            'city',
            'state',
            'country',
            'active',
            'deleted',
        ]

    def user_name_filter(self, queryset, name, value):
        return User.objects.filter(
            Q(first_name__icontains=value) |
            Q(last_name__icontains=value)
        )

On API side it shows below filtes by default,

How to hide django default filters from others except admin user?

I need to hide the filters like first, last, before, after, offset because I don’t want to expose all my data to everyone on the internet.
So basically if is_superuser is true then only those filters should work.

Please guide how to handle this scenario.

Share
Improve this question

1 Answer
1

Reset to default


1

you can override the get_fields() method in the UserFilter class to get the desired behaviour

def get_fields(self):
    fields = super().get_fields()


    if not self.request.user.is_superuser:
        fields.pop('first_name', None)
        fields.pop('last_name', None)
        fields.pop('before', None)
        fields.pop('after', None)
        fields.pop('offset', None)

    return fields

Share
Improve this answer



Leave a Reply

Your email address will not be published. Required fields are marked *