开发者

django accessing foreign key in model

i have the following models

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_开发者_Python百科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

I have the the pk of the class, and I want to find out who are the parents of the students in the selected class.

My feeble attempt is:

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]

Now, I am just curious if there is a shorter or more efficient way of doing this(i'm sure missed something in the docs) ?


This should work

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

"To refer to a "reverse" relationship, just use the lowercase name of the model". (docs)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜