具有特定键的 Django ManyToMany 反向查询
Django ManyToMany reverse query with specific key
我有两个 table。首先,是基本用户 table。第二个是 table 称为 Section.
def User(models.Model):
...
is_teacher = models.BooleanField(default=False)
...
def Section(models.Model):
...
teachers = models.ManyToManyField(User, related_name="teachers")
students = models.ManyToManyField(User, related_name="students")
is_active = models.BooleanField(default=True)
...
我想获取所有学生用户(在用户 table 中用 is_teacher=False
标识),我知道可以用 User.objects.filter(is_teacher=False)
轻松完成。
我想也获取每个用户的活动部分。
但是,目前,我什至无法为用户获取 部分 的集合。
我试过:
students = User.objects.filter(is_teacher=False)
for s in students:
print s.section_set.all()
但是我得到一个错误,指出 User
对象没有 section_set
。我猜是因为该部分与用户 table(教师和学生)有两个多对多关系,我可能必须更清楚地指定关系(跟随学生而不是教师)。但我不确定该怎么做。
试试这个:
sec = Section.object.filter(students = students, is_active=True)
您将获得活跃学生的分区对象。
您已经在 ManyToMany 字段上显式定义了 related_name
,因此这是您应该使用的访问器:
print s.students.all()
并不是说您使用的实际名称没有多大意义;反向关系不是"students",而是"sections as a student".
定义 related_name
值时,请记住这是 backwards 关系的名称(在您的情况下 — 从 User
到 Section
).因此,为了让您的代码清晰易懂,我建议您像这样更改名称:
def Section(models.Model):
...
teachers = models.ManyToManyField(User, related_name="sections_where_teacher")
students = models.ManyToManyField(User, related_name="sections_where_student")
is_active = models.BooleanField(default=True)
...
然后使用关系如下所示:
print s.sections_where_student.all()
我有两个 table。首先,是基本用户 table。第二个是 table 称为 Section.
def User(models.Model):
...
is_teacher = models.BooleanField(default=False)
...
def Section(models.Model):
...
teachers = models.ManyToManyField(User, related_name="teachers")
students = models.ManyToManyField(User, related_name="students")
is_active = models.BooleanField(default=True)
...
我想获取所有学生用户(在用户 table 中用 is_teacher=False
标识),我知道可以用 User.objects.filter(is_teacher=False)
轻松完成。
我想也获取每个用户的活动部分。
但是,目前,我什至无法为用户获取 部分 的集合。
我试过:
students = User.objects.filter(is_teacher=False)
for s in students:
print s.section_set.all()
但是我得到一个错误,指出 User
对象没有 section_set
。我猜是因为该部分与用户 table(教师和学生)有两个多对多关系,我可能必须更清楚地指定关系(跟随学生而不是教师)。但我不确定该怎么做。
试试这个:
sec = Section.object.filter(students = students, is_active=True)
您将获得活跃学生的分区对象。
您已经在 ManyToMany 字段上显式定义了 related_name
,因此这是您应该使用的访问器:
print s.students.all()
并不是说您使用的实际名称没有多大意义;反向关系不是"students",而是"sections as a student".
定义 related_name
值时,请记住这是 backwards 关系的名称(在您的情况下 — 从 User
到 Section
).因此,为了让您的代码清晰易懂,我建议您像这样更改名称:
def Section(models.Model):
...
teachers = models.ManyToManyField(User, related_name="sections_where_teacher")
students = models.ManyToManyField(User, related_name="sections_where_student")
is_active = models.BooleanField(default=True)
...
然后使用关系如下所示:
print s.sections_where_student.all()