[PYTHON] [Django] About one-to-many relationships (related_name, _set.all ())

Introduction

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.

Premise

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. スクリーンショット 2020-06-23 14.55.56.png

The following two cases are divided and each method is considered.

How to refer to many → 1

Can be obtained by object.field name

>>> post1 = Post.object.get(id=1)
>>> post1
<Post:quadratic function>
>>> post1.category
<Category:Math>

1 → How to refer to many [_set.all ()]

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>]>

What is related_name

Added related_name as an argument

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

Take advantage of related_name

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

Recommended Posts

[Django] About one-to-many relationships (related_name, _set.all ())
About django custom filter arguments
About handling Django static files