Greg
Greg

Reputation: 47124

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?)

Upvotes: 8

Views: 9178

Answers (1)

Andrew Wilkinson
Andrew Wilkinson

Reputation: 10846

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.

Upvotes: 7

Related Questions