[Django]-Django Foreign Key QuerySet (join)

5👍

Remember a ForeignKey is a one-to-many relation: there are many Users for each Student. From a user object, you can access the related Students by doing user_obj.student_set.all().

2👍

Adding to Daniel’s answer, you can also use related_names , right now when you have to do a reverse foreign-key lookup, you need to write :-

user_obj.student_set.all()

However, with related_name attribute, the model would look like :-

class Student(models.Model):
    user = models.ForeignKey(User, related_name='studentuser')
    nr_indeksu = models.BigIntegerField()

    def __unicode__(self):
        return unicode(self.user

then for a reverse lookup, you need to write :-

user_obj.studentuser.all()

Basically, all I mean to say is, you can supply own names for reverse lookup by passing related_name attribute, if in case you don’t want to use the default name used by django which is generally of the form <foreign_key_name>_set eg. in your case it is student_set.

0👍

s =  Student.objects.get(user__id=2)

s.nr_indeksu

Leave a comment