我有以下型号
class SchoolClass(models.Model):
id = models.AutoField(primary_key = True)
class_name = models.TextField()
level = models.IntegerField()
taught_by = models.ManyToManyField(User,related_name="teacher_teaching",through='TeachSubject')
attended_by = models.ManyToManyField(User,related_name='student_attending')
def __unicode__(self):
return self.class_name
class Meta:
db_table = 'classes'
class Relationship(models.Model):
rChoices = (
(1,'Mother'),
(2,'Father'),
(3,'Guardian'),
)
parent = models.ForeignKey(User,related_name='parent')
student = models.ForeignKey(User,related_name='child')
relationship = models.IntegerField(choices= rChoices)
#add in __unicode__ for admin name
class Meta:
unique_together = ('parent','student')
db_table = 'relationship
我有班级的PK,我想找出谁是所选班级学生的家长。
我的微弱尝试是:
selected_class = SchoolClass.objects.get(pk=class_id)
studs = selected_class.attended_by.all().select_related()
r = Relationship.objects.filter(student__in=students)
parents = [.parent for p in r]
现在,我只是好奇是否有更短或更有效的方法(我肯定错过了文档中的内容)?
答案 0 :(得分:2)
这应该有效
parents = Relationship.objects.filter(student__schoolclass__id=class_id).values_list('parent', flat=True)
“要引用”反向“关系,只需使用模型的小写名称”。 (docs)