How to filter API results by related model attribute using Tastypie?

Given the following API definition, I should be able to filter events by product alias.

Given that the event belongs to the task and the task belongs to the product, I am not sure how to specify it.

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????
        }
+3
source share
2 answers

Given the following filtering characteristics:

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

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

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

You must be able to:

/api/events/job__product__alias=something
+11
source

. , tastypie ForeignKey. , 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

:

/api/events/?job__product__alias=something
0

All Articles