[Fixed]-How can I make a django query-set that uses two classes?

1đź‘Ť

âś…

You don’t need a special query, the leader attribute on the Department object gives you access to a full Person object, with all its properties:

department = Department.objects.get(pk=1)
print(department.leader.salary)

Behind the scenes the code above will generate two SQL queriers. To make sure only one query is issued you can optionally use select_related:

department = Department.objects.select_related('leader').get(pk=1)
print(department.leader.salary)

This way Django will fetch information about the leader’s Person object during the original query (instead of the usual “lazy” approach of waiting until it is actually needed). This however is only an optimization and often times isn’t really needed.


In case you want to filter a queryset using a field from an object across a relationship, you can use the __ notation, which represents the relationship between two models:

departments = Department.objects.filter(leader__salary=100)

Leave a comment