related name in django

Solutions on MaxInterview for related name in django by the best coders in the world

showing results for - "related name in django"
Sebastián
28 Nov 2018
1Let's say you have a model named Book and a model named Category. Each book has one and only one category, denoted by a foreign key. Thus, you'll have the following models:
2
3class Category(models.Model):
4  name = models.CharField(max_length=128)
5
6class Book(models.Model):
7  name = models.CharField(max_length=128)
8  category = models.ForeignKey('Category')
9Now, when you have a Book instance you can refer to its category using 
10the corresponding field. Furthermore, if you have a category instance,
11by default, django adds an attribute to it named book_set which returns
12a queryset with all the books that have this specific category.
13So you can do something like:
14
15category = Category.objects.get(pk=1)
16print "Books in category {0}".format(category.name)
17for book in category.book_set.all():
18  print book.name
19Now, book_set is an attribute that django constructed for us and gave it this
20name by default. Using the related_name attribute of foreign key you can give
21this attribute whatever name you want (for example if I had definited category
22                                       as this
23                                       category = models.ForeignKey('Category', related_name='book_collection') then instead of category.book_set.all() I'd use category.book_collection.all()).
24
25In any case, you rarely need to change the related_name, if at all in usual case 
26                                       (I don't recommend it because it's easy to remember the django default x_set).
27                                       However there's a use case where it is required: When you have multiple
28                                       foreign keys from a model to another. 
29                                       In this case there would be a clash (since django would try to create two x_set attributes to the same model) and you need to help by naming 
30                                       the x_set attributes yourself.
31
32For example, if my Book model was like this (had a category and a subcategory):
33
34class Book(models.Model):
35  name = models.CharField(max_length=128)
36  category = models.ForeignKey('Category')
37  sub_category = models.ForeignKey('Category')
38then the model would not validate unless you give one (or both) of the 
39                                       ForeignKeys a related_name attribute so that the clash will be resolved. 
40                                       For example you could do something like this:
41
42class Book(models.Model):
43 name = models.CharField(max_length=128)
44  category = models.ForeignKey('Category', related_name='book_category_set')
45  sub_category = models.ForeignKey('Category', related_name='book_sub_category_set')