Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - Raw SQL Queries - What Happens in Joins

I'm reading that I can use raw SQL in Django and have Django actually build my models from the results.

However I'm wondering what happens if I use joins in the raw SQL. How will Django know what models to use?

(Are there any other issues I should be aware of?)

like image 601
Greg Avatar asked Jun 06 '11 13:06

Greg


1 Answers

It's not the joins that matter, but the column names. You could, for example, do the following:

SELECT table.id, other_table.name AS name from table join other_table using (id)

and pass that into your table model. Django would then treat the names from other_table as though they were names from table and give your normal table instances. I can't imagine why you would want to do that though...

The important thing to remember is that Django is using a very simple mapping from your SQL to its model structure. You can subvert it if you want, but you'll probably end up with some hard to maintain code.

like image 165
Andrew Wilkinson Avatar answered Nov 23 '22 22:11

Andrew Wilkinson