Django: newbie question on Model managers
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 simplicit开发者_JAVA技巧y 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 aggregate
method.
from django.db.models import Sum
value = place.placeref_set.aggregate(Sum('value'))
Now value
is a dictionary with a single value containing the sum of all the values in the associated PlaceRefs.
You can also add this as an attribute of place
class Place(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=300)
@property
def placeref_total(self):
do your calculation here as suggested in Daniel's answer
value = self.placeref_set.aggregate(Sum('value'))
return value
then you can refer to it in your code:
myplace = Place.objects.get(id=x)
myplace.placeref_total
If you don't use the @property decorator, then refer to it as: myplace.placeref_total()
精彩评论