Home > Enterprise >  Django queryset filtering not providing expected behavior
Django queryset filtering not providing expected behavior

Time:11-28

I have an app taking inputs from a user on the front end.

The functionality I'm trying to implement should display all titles on the front end that have reviews <=0, or display NULL values in the database.

 reviewsign_high = 'lte'
 if reviewinput_high == '0':
        review_kwargs = {
                'amz_reviews__isnull': True,
                'amz_reviews__{}'.format(reviewsign_high): float(reviewinput_high)
            }

        titles = titles.filter(**review_kwargs)

However, I don't get any results back here. If I remove one parameter, i.e. 'amz_reviews__isnull': True, I do get all titles with reviews less than or equal to 0.

Vice versa, if I remove 'amz_reviews__{}'.format(reviewsign_high): float(reviewinput_high), I get all titles with NULL reviews. But them together, displays 0 results. Any ideas on a solution here? Thanks!

CodePudding user response:

Multiple filters in Django's ORM default to 'AND' when generating SQL. You should look into using the Q object to specify an 'OR' query. https://docs.djangoproject.com/en/3.2/topics/db/queries/#complex-lookups-with-q-objects

from django.db.models import Q
titles = titles.filter(Q(**review_kwargs, _connector=Q.OR))
  • Related