[Answered ]-Django get model with foreign key

2👍

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

0👍

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).
👤viron

Leave a comment