tags:

views:

61

answers:

2

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.

A: 

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()
Daniel Roseman
Well that sort of works. It returned a list of user ids alright, but it didn't group them at all:Comment.objects.all().filter(content_type=48, object_pk="88").values_list('user_id', flat=True)[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
Daniel Quinn
Sorry, needed to add `distinct`. Updated.
Daniel Roseman
I tried that too, still no joy. I assume that the .distinct() s working on the assumption that it's comparing all values in the table and not just user_id. But yes, even with .distinct() the result is a list of identical user ids.
Daniel Quinn
+2  A: 

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.

maersu
That's exactly what I needed, though to me, it still seems way more complicated than SQL. Thanks for the tip, it works like a charm :-)
Daniel Quinn