简体   繁体   English

在django中查询相关的model-attributes

[英]Querying related model-attributes in django

I have the following custom user model arrangement.我有以下自定义用户模型安排。

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

```

I am able to a query the students based on the location of their teacher (current user).我可以根据老师(当前​​用户)的位置查询学生。

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

I can also query the user model & find all teachers/students我还可以查询用户模型并找到所有教师/学生

    User.objects.filter(is_teacher=True)

QUESTION: Without relying on the profile models (Student & Teacher) How can I extend the query on abstractuser using profile attributes.问题:不依赖配置文件模型(学生和教师)如何使用配置文件属性扩展对抽象用户的查询。

[X]-This is wrong but the idea is something like; [X]-这是错误的,但想法是这样的;

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

You can follow the OneToOneField in reverse:您可以反向遵循OneToOneField

User.objects.filter(teacherprofile__location='newyork')

You thus do not need to store is_teacher and is_student explicitly.因此,您不需要显式存储is_teacheris_student You can simply filter Student s with:您可以简单地过滤Student s:

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

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

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