2011-05-20 75 views
1

访问外键我有以下型号Django的模型

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] 

现在,我只是好奇,如果有这样做(我敢肯定错过了在文档的东西)的一个较短的或更有效的方法是什么?

回答

2

这应该工作

parents = Relationship.objects.filter(student__schoolclass__id=class_id).values_list('parent', flat=True) 

“来指代‘反向’的关系,只是使用模型的小写名称”。 (docs