I’m new to Django and I’d like to understand how to use managers. I’ve read the documentation but need a little help putting it into practice.
I’ve got models as follows:
class Place(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=300)
class PlaceRef(models.Model):
place = models.ForeignKey(Place)
entry = models.ForeignKey(Entry)
value = models.FloatField()
units = models.CharField(max_length=30)
If I had a particular Place, should I use a Manager to add up the value of all the PlaceRefs associated with it? (assuming for the sake of simplicity that all the units are the same…)
place = Place.objects.get(id=id)
value = PlaceRef.objects... # what to do here?
No need for a new manager here. There’s already an automatic manager that deals with the relationship between Place and PlaceRef – it’s accessed via
place.placeref_set.But to add up the values, you need to use aggregation – specifically, the
aggregatemethod.Now
valueis a dictionary with a single value containing the sum of all the values in the associated PlaceRefs.