我可以在django模型中使用这样的注释吗?

时间:2016-07-26 17:28:39

标签: python django django-models django-templates

models.py

matches = models.ManyToManyField('Matches')
...
def get_rating(self):
  from django.db.models import Sum, Value, IntegerField
  from django.db.models.functions import Coalesce

  return self.matches.annotate(rating=Coalesce(Sum('matches__rating_difference'), Value(0), output_field=IntegerField()) + Value(1000))

rating_difference包含玩家评分

get_rating应该返回积分总和(玩家评分)

template.html

{{ player.matches.get_rating.(?)rating }}

1 个答案:

答案 0 :(得分:0)

有效

models.py

matches = models.ManyToManyField('Matches')
...
def get_rating(self):
  from django.db.models import Sum, Value, IntegerField
  from django.db.models.functions import Coalesce

  return self.matches.aggregate(rating=Coalesce(Sum('rating_difference'), Value(0), output_field=IntegerField()) + Value(1000))

template.py

{{ player.matches.get_rating.rating_difference }}