【问题标题】:Django ManyToMany reverse query with specific key具有特定键的 Django ManyToMany 反向查询
【发布时间】:2015-06-01 16:17:48
【问题描述】:

我有两张桌子。第一个是基本的用户表。第二个是一个名为 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)
    ...

我想获取所有学生用户(在用户表中使用is_teacher=False 标识),我知道这可以通过User.objects.filter(is_teacher=False) 轻松完成。

我想获取每个用户的活动部分。

但是,目前,我什至无法为用户获取 sections 集。

我试过了:

students = User.objects.filter(is_teacher=False)
for s in students:
    print s.section_set.all()

但是我收到一个错误,User 对象没有 section_set。我猜是因为该部分与用户表(教师和学生)有两个多对多关系,我可能必须更清楚地指定关系(跟随学生而不是教师)。但我不知道该怎么做。

【问题讨论】:

    标签: django postgresql manytomanyfield


    【解决方案1】:

    在定义related_name 值时,请记住这是backwards 关系的名称(在您的情况下——从UserSection)。因此,为了让您的代码清晰易懂,我建议您更改如下名称:

    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()
    

    【讨论】:

    • 谢谢。现在开始了解related_names 字段的真正用途...
    【解决方案2】:

    试试这个:

    sec = Section.object.filter(students = students, is_active=True)
    

    您将获得活跃学生的部分对象。

    【讨论】:

      【解决方案3】:

      您已经在 ManyToMany 字段上明确定义了related_name,因此这是您应该使用的访问器:

      print s.students.all()
      

      并不是说您使用的实际名称没有多大意义;反向关系不是“学生”,而是“作为学生的部分”。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-11
        • 2017-06-03
        • 1970-01-01
        • 2013-06-08
        • 2017-09-08
        • 2020-07-18
        相关资源
        最近更新 更多