Sander Bakker
Sander Bakker

Reputation: 497

Django ORM query returning wrong result using Q

I have the following query using Django ORM:

fixtures = Fixture.objects.annotate(oc=Count('odds__id')).filter((Q(odds__result=4) | Q(oc__lt=10)), date__year__gte=2016).distinct()

Where it should retrieve all the fixtures with an odds object having result set to 4 OR where the count of odds objects is lower than 10.

When I execute this query it returns 34 fixtures objects, but when executing:

fixtures = Fixture.objects.annotate(oc=Count('odds__id')).filter(oc__lt=10, date__year__gte=2016).distinct()

It returns +30k of fixture objects.

How can I get the first query to return the same amount of objects (or at least closer to 30k objects) as the second query? And why is this OR clause not working properly?

Upvotes: 0

Views: 140

Answers (1)

Benbb96
Benbb96

Reputation: 2283

Maybe add distinct=True in the annotation :

fixtures = Fixture.objects.annotate(oc=Count('odds__id', distinct=True)).filter((Q(odds__result=4) | Q(oc__lt=10)) & Q(date__year__gte=2016)).distinct()

Upvotes: 1

Related Questions