与 django 重组作斗争

发布于 2024-10-16 21:08:46 字数 679 浏览 2 评论 0原文

我有两个型号。

一个项目和一个支持者模型。

我基本上想运行一个查询来返回拥有最多支持者的项目。

重组是实现这一目标的唯一途径吗?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不再让梦枯萎 2024-10-23 21:08:46

我不确定你在重组方面做了什么,但支持者最多的项目是:

Project.objects.annotate(Count('backer')).latest('backer__count')

使用注释
http://docs.djangoproject.com/en/dev/topics/db/聚合/

如果您想要 10 个最受支持的项目,则将是

Project.objects.annotate(Count('backer')).order_by('-backer__count')[:10]

更新:我发现您可能指的是“金额”,如字段 Backer.amount 中所示,在这种情况下,您将修改查询以使用django.db.models.Sum

Project.objects.annotate(amount = Sum('backer__amount')).order_by('-amount')[:10]

I'm not sure what you're doing with regroup, but the project with the most number of backers is:

Project.objects.annotate(Count('backer')).latest('backer__count')

Using annotation
http://docs.djangoproject.com/en/dev/topics/db/aggregation/

If you wanted the 10 most backed projects, it would be

Project.objects.annotate(Count('backer')).order_by('-backer__count')[:10]

Update: I see you might mean "amount" as in the field Backer.amount, in which case you would modify the query to use django.db.models.Sum.

Project.objects.annotate(amount = Sum('backer__amount')).order_by('-amount')[:10]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文