简体   繁体   English

如何制作使用两个类的Django查询集?

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

How can I link two classes in a django query set. 如何在Django查询集中链接两个类。 For example I have a class Person and a class Department. 例如,我有一个Person类和一个Department类。 A person has an attribute salary and a Department has the attribute leader. 一个人有一个属性工资,部门有一个属性负责人。 How can I do a query that gives me the salary of the leader of a department. 我该如何查询一个部门负责人的薪水。

I am happy for any help :) 我很乐意提供帮助:)

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对象上的leader属性使您可以访问具有其所有属性的完整Person对象:

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

Behind the scenes the code above will generate two SQL queriers. 在后台,上面的代码将生成两个SQL查询器。 To make sure only one query is issued you can optionally use select_related : 为了确保只发出一个查询,您可以选择使用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). 这样,Django将在原始查询期间获取有关领导者的Person对象的信息(而不是通常等到实际需要时才使用的“懒惰”方法)。 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM