Reputation: 1054
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 Person.objects.filter(name=David).select_related('Role')
Because Role is not Person's attribute. Is there anyway I can get this with only 1 hit to DB?
Upvotes: 1
Views: 2796
Reputation: 599490
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:
Role.objects.filter(person__name='David')
Upvotes: 2
Reputation: 19
To get the persons, it is as you already wrote:
Person.objects.filter(name='David')
To get all the roles related to any person called David:
Role.objects.filter(person__name='David')
To get the roles of a given person:
Role.objects.filter(person=person)
So what I understand from your question is that you want to do something like this:
for person in Person.objects.filter(name='David'):
person_roles = Role.objects.filter(person=person)
# ...
# do something with person_roles (that should contain
# at most one object according to your constraints).
Upvotes: 0