What does related_name do?

前端 未结 2 866
隐瞒了意图╮
隐瞒了意图╮ 2020-12-31 21:39

In the Django documentation about related_name it says the following:

The name to use for the relation from the related object back to th

2条回答
  •  失恋的感觉
    2020-12-31 22:03

    When you create a foreign key, you are linking two models together. The model with the ForeignKey() field uses the field name to look up the other model. It also implicitly adds a member to the linked model referring back to this one.

    class Post(models.Model):
        # ... fields ...
    
    class Comment(models.Model):
        # ... fields ...
        post = models.ForeignKey(Post, related_name=???)
    

    There are three possible scenarios here:

    1. Don't specify related_name

    If you don't specify a name, django will create one by default for you.

    some_post = Post.objects.get(id=12345)
    comments = some_post.comment_set.all()
    

    The default name is the relation's name + _set.

    2. Specify a custom value

    Usually you want to specify something to make it more natural. For example, related_name="comments".

    some_post = Post.objects.get(id=12345)
    comments = some_post.comments.all()
    

    3. Prevent the reverse reference from being created

    Sometimes you don't want to add the reference to the foreign model, so use related_name="+" to not create it.

    some_post = Post.objects.get(id=12345)
    comments = some_post.comment_set.all() # <-- error, no way to access directly
    

    related_query_name is basically the same idea, but when using filter() on a queryset:

    posts_by_user = Post.objects.filter(comments__user__id=123)
    

    But to be honest I've never used this since the related_name value is used by default.

提交回复
热议问题