[Django]-How do I filter API results by a related model attribute using Tastypie?

11👍

Given the following filtering specs:

# In EventResource
filtering = { 
   'job' : ALL_WITH_RELATIONS
}

# In JobResource
filtering = { 
   'product' : ALL_WITH_RELATIONS
}

# In ProductResource
filtering = {
    'alias' : ALL
}

You should be able to do:

/api/events/job__product__alias=something
👤kgr

0👍

A simple way to achieve this is by Advanced Filtering. This avoids many queries generated by tastypie ForeignKey fields. For security, remember to validate or clean your filter input data manually before adding data to orm_filters.

class EventResource(ModelResource):

    class Meta:
        queryset = Event.objects.all()
        resource_name = 'event'
        allowed_methods = ['get']

    def build_filters(self, filters=None):

        if filters is None:
            filters = {}

        orm_filters = super(EventResource, self).build_filters(filters)

        # Your filtering
        if 'job__product__alias' in filters:
            orm_filters['job__product__alias'] = filters.get(
                'job__product__alias')

    return orm_filters

Them you should be able to get the filtered results doing:

/api/events/?job__product__alias=something

Leave a comment