postgresql - Django ManyToMany reverse query with specific key -
i have 2 tables. first, basic user table. , second table called 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) ...
i student users (identified in user table is_teacher=false
) know can done user.objects.filter(is_teacher=false)
.
i also active section(s) each user.
but, @ moment, can't seem set of sections users.
i've tried:
students = user.objects.filter(is_teacher=false) s in students: print s.section_set.all()
but i'm getting error user
object has no section_set
. i'm guessing because section has 2 many many relationships user table (teachers , students), have specify relationship more (to follow students 1 not teachers one). i'm not sure how this.
when defining related_name
value, keep in mind name backwards relation (in case — user
section
). so, keep code clear , easy understand, i'd recommend change names this:
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) ...
then using relations looks this:
print s.sections_where_student.all()
Comments
Post a Comment