[Django]-Using related_name correctly in Django

24👍

Yes, classes is a manager. It can be several classes for one teacher. So to output their names you should do:

john = Student.objects.get(username='john')
for class2 in john.classes.all():
   print class2.name

If you want only one class for one student then use one-to-one relation. In this case you can access the related field with your method.

3👍

Just be aware: you are defining a 1-many relationship. Thus, student could have multiple classes, therefore john.classes.name cannot work, since you have not specified the class of which you want to have the name. in john.classes “classes” is just a manager that you can use like any other Django Model Manager. You can do a john.classes.all() (like sergzach propsed), but also things like john.classes.get(…) or john.classes.filter(…).

1👍

you can do like this to access the first row in the table

john = Student.objects.get(username = 'john')    
john.classes.all().first().name # to access first row
john.classes.all().last().name # to access last row

in the above example you don’t want to iterate over the objects

it will give you the name of the class in the first row

Leave a comment