0

Say, I have the following two Django models:

class Author(models.Model):
    name = models.CharField(max_length=100)

class Book(models.Model):
    name = models.CharField(max_length=300)
    pages = models.IntegerField()
    author = models.ForeignKey(Author)

With django-filter, how can I write a FilterSet, that allows me to filter somewhat like:

Author.objects.filter(
    (Q(book__name__contains='How') & Q(book__pages=100)) |
    (Q(book__name__contains='Why') & Q(book__pages=50))
)

That is, I want to have a set of filter Fields, that are all applied to a related model and that I can combine. In my case, that set contains many more fields, so a custom MultiValueField is probably not really applicable.

Is there any standard way to solve this using django-filter, or should I implement my own filtering logic in the view?

2
  • What would the request querystring look like here? How would you differentiate the two sets of Q objects that you want to filter by? Commented Nov 16, 2016 at 3:23
  • ?book_name_1=How&book_pages_2=100&book_name_2=why&book_pages_2=50 Commented Nov 16, 2016 at 7:37

1 Answer 1

2

If you want to keep this in the FilterSet, rather than pushing back up to the view, your best bet is to override the qs property and add the multi-value filtering logic there.

(A field with a custom method provides validation but still only takes a single value — so you'd need to pull the others from the parent anyway — as such, overriding qs seems clearer.)

Sign up to request clarification or add additional context in comments.

2 Comments

I thought so, and decided that just doing it manually in the view with a standard django form would be an easier and more readable solution. However, your answer is still the correct way to go with django-filter, so I'll accept it.
Yep, fair enough. Django Filter's scope is "common filtering problems" — uncommon ones may still require doing it by hand. :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.