如何让 GROUP BY 在我想要所有字段和对象的地方使用 Django ORM
我需要按用户对所有条目进行分组,并执行如下操作来获取计数:
class Promotion(models.Model):
pass
class Entry(models.Model):
user = models.ForeignKey('User');
promotion = models.ForeignKey('Promotion')
def get_uniques(promotion_id):
promotion = Promotion.objects.get(promotion_id)
entries = promotion.entry_set.annotate(Count('user'))
return entries
但是它多次返回同一用户。在查看 StackOverflow 后,我还尝试了以下操作,它似乎正在做一些与我想要的不同的事情:
promotion.entry_set.annotate(Count('user')).order_by('user')[:10]
promotion.entry_set.all().values('user').annotate(entry_count=Count('user')).order_by()
Entry.objects.filter(promotion=promotion).annotate(Count('user')).order_by('user')
基本上我正在尝试这样做,为每个用户提供一个 Entry 对象:
Entry.objects.raw("""
SELECT *
FROM promotion_entry
WHERE promotion_id = %s
GROUP BY user_id""", (promotion_id,))
然后我将执行第二个查询获取条目数,仍然不理想。我可以在没有 raw 的情况下进行 GROUP BY 吗?
似乎有一张票可以让我通过启用 DISTINCT ON
在 bugtracker 上做我想做的事情:
I need to group all entries by user and get the count doing something like this:
class Promotion(models.Model):
pass
class Entry(models.Model):
user = models.ForeignKey('User');
promotion = models.ForeignKey('Promotion')
def get_uniques(promotion_id):
promotion = Promotion.objects.get(promotion_id)
entries = promotion.entry_set.annotate(Count('user'))
return entries
However it's returning the same user multiple times. I've also tried the following after looking around StackOverflow, and it seem to be doing something other than what I want:
promotion.entry_set.annotate(Count('user')).order_by('user')[:10]
promotion.entry_set.all().values('user').annotate(entry_count=Count('user')).order_by()
Entry.objects.filter(promotion=promotion).annotate(Count('user')).order_by('user')
Basically I'm trying to do this, giving me an Entry object for each user:
Entry.objects.raw("""
SELECT *
FROM promotion_entry
WHERE promotion_id = %s
GROUP BY user_id""", (promotion_id,))
Then I'll perform a second query to get the entry count, still not ideal. Can I do a GROUP BY without raw?
There seem to be a ticket that would let me do what I want in the future over on the bugtracker by enabling DISTINCT ON
: https://code.djangoproject.com/ticket/6422
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您想对每个用户使用的条目进行计数:
如果您想为每个用户使用一些条目:
这将为您提供条目的
id
,请使用__in
获取对象他们自己。If you want to count entries for each user use:
If you want some entry for each user use:
This will give you
id
's of entries, use__in
to get objects themselves.