模型中的 Django 聚合
您好,我正在编写一个网站,该网站将捐赠用作项目中的多个项目。 我正在计算捐款总额,但似乎不起作用。我需要两个模型之间的中间表吗?
我想知道是否有更好的方法来使用 Django Aggregation 来做到这一点。
class Donation(models.Model):
user = models.ForeignKey(User)
amount= models.DecimalField(max_digits=12, decimal_places=2)
def __unicode__(self):
return self.user
class Project(models.Model):
name = models.CharField(max_length=200)
donations=models.ManyToManyField(Donation, null=True, blank=True)
def __unicode__(self):
return self.name
def progress(self):
donations = self.donations.all()
total_donations = 0
for item in donations:
total_donations += item.amount
return total_donations
感谢您的热心帮助!
Hi I'm coding a site that uses donations as multiple items on a Project.
I'm calculating the total amount of donations, but it doesn't seem to work. Do i need an intermediate table between the two models?
I was wondering if there's a better to way to do it with Django Aggregation.
class Donation(models.Model):
user = models.ForeignKey(User)
amount= models.DecimalField(max_digits=12, decimal_places=2)
def __unicode__(self):
return self.user
class Project(models.Model):
name = models.CharField(max_length=200)
donations=models.ManyToManyField(Donation, null=True, blank=True)
def __unicode__(self):
return self.name
def progress(self):
donations = self.donations.all()
total_donations = 0
for item in donations:
total_donations += item.amount
return total_donations
Thanks for your kind help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我将摆脱
progess
方法并简单地注释查询集:您甚至可以使用自定义
Manager
:然后:
或者您甚至可以覆盖默认查询集,因此进度是总是返回:
然后:
I'd get rid of the
progess
method and simply annotate the queryset:You could even use a custom
Manager
:Then:
Or you could even override the default queryset so progress is always returned:
Then:
我想这会给你你想要的。您必须尝试一下,如果有任何问题请告诉我。另外,请确保您的 Django 版本支持聚合。
编辑:修复了没有返回任何内容的问题。
I think that'll give you what you want. You'll have to play with it a bit, and let me know if you have any problems. Also, make sure you version of Django supports aggregation.
EDIT: Fixed a problem where none was being returned.