Search code examples
djangotastypie

How do I filter API results by a related model attribute using Tastypie?


Given the following API definition I need to be able to filter Events by Product Alias.

Given that an Event belongs to a Job and a Job belongs to a Product I'm not sure how to spec that.

api.py:

class ProductResource(ModelResource):

    class Meta:
        queryset = Product.objects.all()
        resource_name = 'product'
        allowed_methods = ['get']
        excludes = ['created_at','updated_at']
        filtering = {
            'alias': ALL
        }

class EnvironmentResource(ModelResource):

    class Meta:
        queryset = Environment.objects.all()
        resource_name = 'environment'
        allowed_methods = ['get']
        excludes = ['created_at','updated_at']

class JobResource(ModelResource):

    product = fields.ForeignKey(ProductResource, 'product')

    class Meta:
        queryset = Job.objects.all()
        resource_name = 'job'
        allowed_methods = ['get']
        excludes = ['created_at','updated_at']

class EventResource(ModelResource):

    environment = fields.ForeignKey(EnvironmentResource, 'environment',full=True)
    job = fields.ForeignKey(JobResource, 'job',full=True)

    class Meta:
        queryset = Event.objects.all()
        resource_name = 'event'
        allowed_methods = ['get']
        excludes = ['created_at','updated_at']
        filtering = {
            HOW DO I FILTER BY PRODUCT ALIAS????
        }

Solution

  • 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