I wrote the following query using the Django ORM:
JavaScript
x
2
1
fixtures = Fixture.objects.filter(league=league).filter((Q(predictions__value__gt=0.0) & Q(predictions__team=F("home"))) & (Q(predictions__value__gt=0.0) & Q(predictions__team=F("away"))))
2
With this I’m trying to filter out each fixture where the prediction__value
for the home is greater than 0.0 and the prediction__value
of the away is greater than 0.0.
Sadly my query is returning 0 records upon using .count()
whereas it should return almost every record.
When I only use one part of the query; so either the home or the away part the query does return a certain amount of records.
The models:
JavaScript
1
13
13
1
class Fixture(models.Model):
2
home = models.ForeignKey(Team, on_delete=models.CASCADE, related_name="home")
3
away = models.ForeignKey(Team, on_delete=models.CASCADE, related_name="away")
4
5
league = models.ForeignKey(League, on_delete=models.CASCADE, blank=True)
6
7
class Prediction(models.Model):
8
fixture = models.ForeignKey(Fixture, on_delete=models.CASCADE, related_name="modelx_predictions")
9
team = models.ForeignKey(Team, on_delete=models.CASCADE)
10
model = models.ForeignKey(Model, on_delete=models.CASCADE, related_name="modelx_predictions")
11
12
value = models.FloatField(default=None, null=True, blank=True)
13
The value of league is irrelevant here.
Advertisement
Answer
You should filter with two outer JOIN’s, so:
JavaScript
1
5
1
fixtures = Fixture.objects.filter(league=league).filter(
2
predictions__value__gt=0.0, predictions__team=F('home')
3
).filter(
4
predictions__value__gt=0.0, predictions__team=F('away')
5
)
This will thus look for Prediction
s in the given fixture
where one prediction is from the home
team and its value is greater than 0
, and a predication from the away
team that is greater than 0
.