code_junkie

Django custom SQL to return QuerySet where each object has additional properties

Nov 13th, 2011
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.58 KB | None | 0 0
  1. squirrel_table
  2. - name
  3. - country_of_origin
  4. - id
  5.  
  6. nut_table
  7. - id
  8. - squirrel_who_owns_me[fk to squirrel]
  9.  
  10. select sq.*,
  11. nut_counts.nut_count
  12. from squirrel_table sq,
  13. (select sq2.id as squirrel_id,
  14. count(nuts) as nut_count
  15. from squirrel_table sq2,
  16. nut_table nuts
  17. where nuts.squirrel_who_owns_me = sq2.id
  18. and sq.country_of_origin = 'USA'
  19. group by sq2.id) as nut_counts
  20. where sq.id = nut_counts.squirrel_id
  21.  
  22. sql = 'select sq.id as pk, sq.* ... %s'
  23. squirreled = squirrel_table.objects.raw(sql, ["arg1"])
Add Comment
Please, Sign In to add comment