Search code examples
djangotastypie

Django Tastypie apply_filter for foreign keys


I have two relational tables with a foreign key -user. And the queryset that is returned to me is as follows

city: null,
contact_address: "",
contact_number: "9874563210",
country: null,
date_of_birth: null,
id: 12,
invitation_text: "Aphabets",
middle_name: "def",
profile_img: null,
resource_uri: "/client/api/v1/profile/12/",
state: null,
user: {
      date_joined: "2014-07-27T04:07:00",
      email: "[email protected]",
      first_name: "abc",
      id: 24,
      is_active: false,
      last_login: "2014-07-27T04:07:00",
      last_name: "ghi",
      resource_uri: "/client/api/v1/user/24/",
      username: "[email protected]"
},
zipcode: n

My api resource is as follows :

class ProfileResource(ModelResource):

user = fields.ToOneField(UserResource,'user', full=True)    

"""docstring for ProfileResource"""
def alter_list_data_to_serialize(self, request, data):
    if request.GET.get('meta_only'):
        return {'meta': data['meta']}
    return data

def authorized_read_list(self, object_list, bundle):

    if (bundle.request.user.is_superuser is True) or (bundle.request.is_staff is True) :
        return object_list.all().select_related()
    else:
        return object_list.filter(user=bundle.request.user).select_related()

def obj_create(self, bundle, **kwargs):
    return super(ProfileResource, self).obj_create(bundle, user=bundle.request.user)

class Meta:
    queryset = UserProfile.objects.filter()
    resource_name = 'profile'
    default_format = 'application/json'
    list_allowed_methods = ['get','post']
    detail_allowed_methods = ['get', 'post', 'put', 'delete', 'patch']
    serializer = Serializer()
    default_format = 'application/json'
    authentication = Authentication()
    authorization = DjangoAuthorization()
    always_return_data = True

I need to filter the query set such a way that only active users should be returned like a filter.

when i tried object_list.filter(is_active = true). I got an error saying "is_active" is not a valid option and options are 'city', 'country' .. etc. How do i refer the relational table value in filters ?

I have seen suggestions to override apply_filter method .. but my question is .. isnt there a way to filter using foreign key values ?

Kindly guide me through this section. Thanks in advance.


Solution

  • Try with :

    object_list.filter(user__is_active = true)
    

    You can find the documentation about this here : https://docs.djangoproject.com/en/1.6/topics/db/queries/#lookups-that-span-relationships