Search code examples
tastypie

Filter users by user group in tastypie


This is my user resource class

class UserResource(ModelResource):
    class Meta:
        queryset = User.objects.all()
        allowed_methods = ['get', 'post', 'put', 'patch']
        resource_name = 'user'
        excludes = ['password']
        #authentication = SessionAuthentication()
        #authorization = DjangoAuthorization()
        authorization = Authorization()
        authentication = Authentication()
        always_return_data = True
        filtering = {
            'id': ALL,
            'username': ALL,
            'groups': ALL_WITH_RELATIONS
        }

I want to filter user by their group names. Like /api/v1/user/?format=json&groups__name=group_name

The above format is not working. How can i filter it in the get request?


Solution

  • You have to add relational fields from model that you are going to use to your resource. In first place you have to create Model resource for Group model. Then create To Many field in UserResource linked to GroupResource.

    Something like this:

    class GroupResource(ModelResource):
        class Meta:
            queryset = Group.objects.all()
            resource_name = 'group'
            authorization = Authorization()
            authentication = Authentication()
            always_return_data = True
            filtering = {
                'id': ALL,
                'name': ALL,
            }
    
    
    class UserResource(ModelResource):
        groups = fields.ToManyField(GroupResource, 'groups',
                                    blank=True)
        class Meta:
            queryset = User.objects.all()
            allowed_methods = ['get', 'post', 'put', 'patch']
            resource_name = 'user'
            excludes = ['password']
            #authentication = SessionAuthentication()
            #authorization = DjangoAuthorization()
            authorization = Authorization()
            authentication = Authentication()
            always_return_data = True
            filtering = {
                'id': ALL,
                'username': ALL,
                'groups': ALL_WITH_RELATIONS
            }
    

    The reason of that is Tastypie has to know relational object authorization, authentication, resource_name and rest bunch of settings that can't populate itself.