在django中查询相关模型属性

Querying related model-attributes in django

我有以下自定义用户模型安排。

```
class User(AbstractUser):
    is_student = models.BooleanField(default=False)
    is_teacher = models.BooleanField(default=False)

class StudentProfile(models.Model):
    student = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
    location = models.CharField(max_length=8, blank=False, default='')
class TeacherProfile(models.Model):
    teacher = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
    location = models.CharField(max_length=8, blank=False, default='')
    gender = models.CharField(max_length=8, choices=GENDER_CHOICES, default='')

```

我可以根据老师(当前​​用户)的位置查询学生。

Student.objects.filter(location=request.user.teacher.location)

我还可以查询用户模型并找到所有 teachers/students

    User.objects.filter(is_teacher=True)

问题: 不依赖个人资料模型(学生和教师)如何使用个人资料属性扩展对 abstractuser 的查询。

[X]-这是错误的,但想法是这样的;

    User.objects.filter(is_teacher=True).filter(is_teacher.location=newyork)

您可以反向关注 OneToOneField

User.objects.filter(<b>teacherprofile__location='newyork'</b>)

因此您不需要显式存储 is_teacheris_student。您可以简单地过滤 Students 与:

# Users with a related StudentProfile record
User.objects.filter(<b>studentprofile__isnull=False</b>)