与 django 重组作斗争
我有两个型号。
一个项目和一个支持者模型。
我基本上想运行一个查询来返回拥有最多支持者的项目。
重组是实现这一目标的唯一途径吗?
class Project(models.Model):
owner = models.ForeignKey(User)
project_name = models.CharField(max_length=50, help_text='Lorem ipsum dolor sit amet.')
class Backer(models.Model):
user = models.ForeignKey(User)
project = models.ForeignKey(Project)
amount = models.PositiveIntegerField()
我尝试了以下操作:
{% regroup backers by project as backers_list %}
{% for obj in backers_list %}
<strong>{{ obj.grouper }}</strong><br />
{% endfor %}
尽管这返回的结果超出了预期。
所以我基本上想获得支持一个项目的支持者总数。
I have two models.
A project and a backers model.
I want to basically run a query that returns the projects with the most backers.
Is regroup the only way to achieve this?
class Project(models.Model):
owner = models.ForeignKey(User)
project_name = models.CharField(max_length=50, help_text='Lorem ipsum dolor sit amet.')
class Backer(models.Model):
user = models.ForeignKey(User)
project = models.ForeignKey(Project)
amount = models.PositiveIntegerField()
I've tried the following:
{% regroup backers by project as backers_list %}
{% for obj in backers_list %}
<strong>{{ obj.grouper }}</strong><br />
{% endfor %}
although this returns more than expected results.
So i basically want to get the total amount of backers that backed a project.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不确定你在重组方面做了什么,但支持者最多的项目是:
使用注释
http://docs.djangoproject.com/en/dev/topics/db/聚合/
如果您想要 10 个最受支持的项目,则将是
更新:我发现您可能指的是“金额”,如字段
Backer.amount
中所示,在这种情况下,您将修改查询以使用django.db.models.Sum
。I'm not sure what you're doing with regroup, but the project with the most number of backers is:
Using annotation
http://docs.djangoproject.com/en/dev/topics/db/aggregation/
If you wanted the 10 most backed projects, it would be
Update: I see you might mean "amount" as in the field
Backer.amount
, in which case you would modify the query to usedjango.db.models.Sum
.