我有三种模式:食物,膳食和膳食计划。
class Food(models.Model):
name = models.CharField(max_length = 30, default="food")
calories = models.FloatField(validators=[validate_positive])
fat = models.FloatField(validators=[validate_positive])
carbs = models.FloatField(validators=[validate_positive])
protein = models.FloatField(validators=[validate_positive])
class Meal(models.Model):
foods = models.ManyToManyField(Food)
@property
def totalcals(self):
sum = self.foods.aggregate(models.Sum('calories'))['calories__sum']
if sum == None:
return 0
else:
return sum
class MealPlan(models.Model):
meals = models.ManyToManyField(Meal)
owner = models.CharField(max_length=14, default= "")
@property
def totalcals(self):
sum = self.meals.foods.totalcals(models.Sum('totalcals'))['totalcals__sum']
if sum == None:
return 0
else:
return sum
第一个totalcals属性正常运行。第二个导致错误。我希望MealPlan中的第二个总膳食能够归还所有用餐总数。有没有办法做到这一点?
答案 0 :(得分:1)
不应该是self.meals.totalcals ...而不是self.meals.foods.totalcals?食物不具有总膳食的特性,但是膳食确实如此。
@property
def totalcals(self):
sum = self.meals.totalcals(models.Sum('totalcals'))['totalcals__sum']
答案 1 :(得分:0)
怎么样?
@property
def totalcals(self):
sum = 0
for meal in self.meals.all():
sum = sum + meal.totalcals
if sum = 0:
return None
else:
return sum
但我想也会有一个较短的答案。