Search code examples
djangotastypie

Django Tastypie filter OR statement


Suppose I'm filtering products in the Django Tastypie API and I want to return all products with product_type = 'cracker' OR product_name = 'oreo'. Using this syntax:

localhost:8000/api?product_type=cracker&product_name__icontains=oreo

This will return products which are crackers AND are named oreo. How can I turn that into an OR statement?


Solution

  • Found the answer. According to the Django query documentation here: https://docs.djangoproject.com/en/2.1/topics/db/queries/#complex-lookups-with-q-objects

    complex queries (such as OR statements) can only be done with the Q() object. Tastypie doesn't have special syntax to handle complex queries in URLs, but you can build custom queries in resources, as in this answer:

    Django Tastypie Advanced Filtering: How to do complex lookups with Q objects