Malyo
Malyo

Reputation: 2000

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?)

Upvotes: 3

Views: 12361

Answers (3)

Siddharth Srivastava
Siddharth Srivastava

Reputation: 1069

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.

Upvotes: 2

Daniel Roseman
Daniel Roseman

Reputation: 599490

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

Upvotes: 5

Joyfulgrind
Joyfulgrind

Reputation: 2836

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

s.nr_indeksu

Upvotes: 0

Related Questions