我有以下型号:
class Client(models.Model):
...
class Document(models.Model):
client = models.ForeignKey(Client, related_name='clients')
...
class MainVoiceActual(models.Model):
doc = models.ForeignKey(Document, related_name='documents')
value = models.IntegerField()
我的目标是在模板中打印属于特定客户的文档的所有值的总和。要执行此操作,我要在calc_total
模型中添加Client
方法。
我尝试了以下但不起作用:
class Client(models.Model):
name = models.CharField(max_length=150)
def calc_total(self):
docs = Document.objects.filter(client=self)
return sum(doc.mainvoiceactuals_set.value for doc in docs)
我收到'Document' object has no attribute 'mainvoiceactuals_set'
错误
答案 0 :(得分:0)
使用它:
def calc_total(self):
voices = MainVoiceActual.objects.filter(doc__client=self)
return sum(voice.value for voice in voices)