I am trying to write a nested query in Django. It is very simple to do in SQL, but with Django I am having some trouble deciding if I am doing it right or not. I have three models. Area, Location, and Measurement.
Area
class Area(models.Model):
name = models.CharField(max_length=200)
longitude = models.FloatField()
latitude = models.FloatField()
Location
class Location(models.Model):
name = models.CharField(max_length=200)
altitude = models.IntegerField()
area = models.ForeignKey(Area, on_delete=models.CASCADE)
Measurement
class Measurement(models.Model):
value = models.FloatField()
date = models.DateTimeField()
location = models.ForeignKey(Location, on_delete=models.CASCADE)
Inside Area, I need a function that will return the average of the measurements for this area. So basically, I need the average measurements of all locations for this area. Area can have many locations, but locations can have one area. In the Area Model, I made this function:
def average_measurement(self):
all_locations = self.location_set.all()
return all_locations.measurement_set.all().aggregate(Avg('value'))
This is my equivalent to writing a nested query in Django. I get all locations first and then find the average of all their measurements. Am I doing this correctly?
On a side question, would this query be equivalent to doing something like this:
avg = 0
locations = self.location_set.all()
sum = 0
counter = 0
for l in locations: measurement = l.measurement_set.all()
if measurement:
for m in measurement:
sum += m.value
counter += 1
if counter != 0:
avg = sum / counter
return avg