Simple group (no account) in Django

If it were raw-SQL, it would be tricky, but in Django it turned out to be quite difficult to find. I want this really:

SELECT
  user_id
FROM
  django_comments
WHERE
  content_type_id = ? AND
  object_pk = ?
GROUP BY
  user_id

      

These are the last two lines that are the problem. I would like to do this "Django-way", but the only thing I found was the mention of aggregates and annotations, which I guess don't solve this problem ... right? If someone could explain this to me, I would really appreciate it.

+2


a source to share


2 answers


As far as I can see, you want the authors of all comments on a specific GenericObject (say in an article).

Djangos ORM offers the following 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 a user 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.

+2


a source


Django is no problem either, but you need to stop thinking in terms of SQL and instead ask yourself what you really want to achieve.

"I want a list of all user IDs who posted comments." Well, then what are you asking for:



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

      

0


a source







All Articles