Open YasirKusay opened 3 months ago
I have an update to this, take a look at the example below:
>>> queryset = FilterAuthorByBook({"books__title__icontains": "othello", "books__genre__icontains": "comedy"})
>>> queryset.qs
<QuerySet []>
The above returns nothing and it appears that your algorithm searches through an Authors books and returns the Author if at least one book contains "othello" in the title AND at least one book is a "comedy". I.e. all the filters we apply must contained by the fields of our books in a non-intersecting manner. Since none of the Books we have for this author is a comedy, the author will not be returned. This makes sense but I would still like to have my original method. Is there a way to do this?
This is standard Django behaviour. See the Spanning multi-valued relationships docs.
If you need to filter in a single step, define a filter that takes both fields from the query data and handles those together. There's an example of that here: https://gitlab.com/-/snippets/2237049
Thank you for that. Taking all of this into account, I have added this filtering method to the FilterAuthorByBook class:
def filter_queryset(self, queryset):
filter_conditions = Q()
filter_data = self.data
for field, value in filter_data.items():
if field.startswith('books__') and value:
filter_conditions &= Q(**{field: value})
queryset = queryset.filter(filter_conditions).distinct()
return queryset
It appears to filter items now as I intended.
Lets say we have an app called:
filter
with 2 models:Author
andBook
where anAuthor
can have manyBook
objects.We also have defined the filter here, where we can filter the
Author
based ontitle
andgenre
of their books:Now lets create an example
We would like to filter authors by the book title "othello" and the "history" book genre. I would expect that nothing would get returned, but it appears that it is filtering the author based on if their book field matches at least one filter we applied, whereas I want the author's books to match all applied fields, for an author to be returned.
Is this the intended behaviour? How can I change it such that the author's books must match all applied fields, for an author to be returned.