Adding annotations to raw sql

112 views
Skip to first unread message

Ruslan Batukaev

unread,
Dec 10, 2014, 6:23:42 PM12/10/14
to django...@googlegroups.com
Suppose I have the following SQL query:

    SELECT a.id, ct, 1 as one
    FROM article a
    LEFT JOIN (
       SELECT article_id, count(distinct(tag)) AS ct
       FROM   article_tag
       WHERE  tag IN ('football', 'tennis', 'django', 'mma')
       GROUP  BY article_id
       ORDER  BY ct
       ) t ON t.article_id = a.ID
    ORDER BY t.ct DESC NULLS LAST
       , (a.blog = 'ign.com') DESC NULLS LAST
       , rating DESC NULLS LAST;

Now execute it in Django:

    Article.objects.raw(query);


According to [Django documentation][1], the queryset will contain the values of `ct` and `one` for each article. However, while it prints the value of `one` correctly, it does not for `ct` and just returns `null`. Is there any way to get `ct` for each article?
Thanks. 

  


john

unread,
Dec 11, 2014, 12:11:56 AM12/11/14
to django...@googlegroups.com
should that be "t.ct"
Johnf
--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/5a93348a-6d18-4735-988e-5cbadc6ca245%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages