Nicky Mirfallah Nicky Mirfallah - 4 months ago 13x
SQL Question

django get model with foreign key

Let's say I have 2 tables in my DB. One of them is called Person which has attributes 'name' and 'id' and the other one is called Role which has attributes 'person'(which is a foreign key to the id in Person table) and 'id'.
Now I'd like to make a query that given a name like David, finds all the persons with that name and also returns the Roles associated with them. We know that every Person is associated to at most 1 role.

I know that I cannot use

Because Role is not Person's attribute. Is there anyway I can get this with only 1 hit to DB?


This is in fact a very simple query, contrary to some of the other answers. The thing to remember is that if you want Roles, you should start with the Role model. So just follow the relationships backwards from there: