简体   繁体   中英

Django Foreign Key QuerySet (join)

So I'm learning Django and trying to get values throught foreign key by using Django ORM functions only. I've got 2 tables: User Table (default Django auth_user system table) and Student Table containing student_id, user_id(FK) and nr_indeksu (it's a number containing additional info for student specific information).

class Student(models.Model):
    user = models.ForeignKey(User)
    nr_indeksu = models.BigIntegerField()

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

I want to fetch nr_indeksu through User model. In other words execute this query (using QuerySet):

SELECT nr_indeksu FROM auth_user
INNER JOIN courses_student on auth_user.id = courses_student.user_id;

I have tried using select_related() function:

u = User.objects.select_related().get(pk=2)

but when i try to access nr_indeksu:

u.nr_indeksu

i got error that User object has no attribute (it makes sense because nr_indeksu is in Student model but shouldn't i be able to fetch it from User?)

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() .

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 .

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

s.nr_indeksu

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM