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
.
- [Django]-How to set PYTHONPATH on web server
- [Django]-How do I fix this error in Python Django involving request.user.is_authenticated() and bool object not callable?
- [Django]-Customize queryset in django-filter ModelChoiceFilter (select) and ModelMultipleChoiceFilter (multi-select) menus based on request
- [Django]-Why does <myproject>/accounts/profile/ show the <myproject>/profile/ page
Source:stackexchange.com