开发者

A simple group-by (no count) in Django

If this were raw-SQL, it'd be a no-brainer, but in Django, this is proving to be quite difficult to find. What I want is this really:

SELECT
  user_id
FROM
  django_comments
WHERE
  content_type_id = ?开发者_开发问答 AND
  object_pk = ?
GROUP BY
  user_id

It's those last two lines that're the problem. I'd like to do this the "Django-way" but the only thing I've found is mention of aggregates and annotations, which I don't think solve this issue... do they? If someone could explain this to me, I'd really appreciate it.


As far as i can see you want to have the authors of all comments of a specific GenericObject (say Article).

Djangos ORM offers following of relationships So the solution would be:

from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType

User.objects.filter(comment_comments__content_type=ContentType.objects.get(app_label="articles", model="article"), comment_comments__object_pk="12").distinct()

if you like to have the users id, use things like values_list or values

User.objects.filter(comment_comments__content_type=ContentType.objects.get(app_label="articles", model="article"), comment_comments__object_pk="12").distinct().values_list('id')

Hope it helps.


It's a no-brainer in Django as well, but you need to stop thinking in terms of SQL and instead ask yourself what you actually want to achieve.

"I want a list of all user IDs who have posted comments." Well then, that's what you ask for:

 Comment.objects.filter(
    content_type_id=foo, object_pk=bar
 ).values_list('user_id', flat=True).distinct()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜