如何在 Django 中进行以下查询?

How to make the following query in Django?

我有一堆用户在一个组里。我还与每个用户建立了 Profile 模型的 OneToOne 关系。

我正在尝试获取特定 学校.教师的所有用户。

我有一个 Teacher 群组,所以我用

过滤了用户
teachers = User.objects.filter(groups__name='Teacher')

以下为简介模型

class Profile(TimeStamped):
    user = models.OneToOneField(User)
    school = models.ForeignKey(School, blank=True, null=True)

假设我要过滤的学校实例分配给一个名为 school.

的变量

我现在如何在 teachers 变量上放置第二个过滤器以仅查找特定 school.

的教师

查询集过滤器可以是 chained

The result of refining a QuerySet is itself a QuerySet, so it’s possible to chain refinements together.

teachers = User.objects.filter(groups__name='Teacher').filter(profile__school=school)

也可以在过滤器中添加条件

teachers = User.objects.filter(groups__name='Teacher',profile__school=school)

更新以澄清评论中提出的观点

这种事情行得通,因为外键看起来行得通,向后也行。引用手册:

It works backwards, too. To refer to a “reverse” relationship, just use the lowercase name of the model.

您使用的原始查询以这种方式引用组 table。