There is a parameter called related_name in the argument of models.ForeignKey () used when associating models with each other in Django, but I did not know when it will be used, so I checked it.
This time, we will create a Category model and a Post model as follows.
apps/models.py
class Category(models.Model):
name = models.CharField(max_length=100)
slug = models.SlugField(unique=True)
def __str__(self):
return self.name
class Post(models.Model):
category = models.ForeignKey(to=Category, on_delete=models.CASCADE)
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
title = models.CharField(max_length=100)
content = models.TextField()
def __str__(self):
return self.title
Suppose that the above code generates 3 categories and 6 posts, and has the relationship shown in the following figure.
The following two cases are divided and each method is considered.
Can be obtained by object.field name
>>> post1 = Post.object.get(id=1)
>>> post1
<Post:quadratic function>
>>> post1.category
<Category:Math>
Can be obtained with object.model name (lowercase) _set.all ()
>>> category3 = Category.object.get(id=3)
>>> category3
<Category:society>
>>> category3.post_set.all()
<QuerySet [<Post:Ryoma Sakamoto>, <Post:Kamakura Shogunate>]>
model name (lowercase) _set
.category3.post_set.all()
→→ category3.posts.all()
apps/models.py
class Category(models.Model):
name = models.CharField(max_length=100)
slug = models.SlugField(unique=True)
class Post(models.Model):
category = models.ForeignKey(to=Category, on_delete=models.CASCADE, related_name='posts') #add to
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
title = models.CharField(max_length=100)
content = models.TextField()
>>> category3 = Category.object.get(id=3)
>>> category3
<Category:society>
>>> category3.posts.all() #Change
<QuerySet [<Post:Ryoma Sakamoto>, <Post:Kamakura Shogunate>]> #← The result is the same