Search code examples
sqldjangowhere-clauserawsql

Django placing of WHERE in raw SQL query


The order of the WHERE in this query was wrong, but it is correct now.

postModel = list(PostModel.objects.raw(
SELECT max(pub_date), 
   count(topic_id) AS freq, 
   count(DISTINCT author) AS contributors 
   FROM crudapp_postmodel 
   WHERE author = "art" 
   GROUP BY topic_id 
   ORDER BY pub_date DESC
))

Thanks


Solution

  • Simple:

    SELECT max(pub_date), 
           count(topic_id) AS freq, 
           count(DISTINCT author) AS contributors 
           FROM crudapp_postmodel 
           WHERE author = "art" 
           GROUP BY topic_id 
           ORDER BY pub_date DESC