In Django's database operation model, how to get all the "many" in a one-to-many or many-to-many relationship? (Using special properties: reverse relationship manager)

When a model is related to another model via a foreign key or a many-to-many field, Django automatically generates an inverse relationship manager for that model. The name of this inverse relationship manager is _setgenerated by appending the model class name. On the inverse relationship manager, you can use various query methods to access related objects.

Let's illustrate with an example. Let's say you have a Postmodel and a Commentmodel that can have multiple comments per post. In this case your model might look like this:

from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()

class Comment(models.Model):
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    text = models.TextField()

In the model, Django will automatically generate an inverse relationship manager Postfor you called . comment_setYou can use the relationship manager to access comment objects related to a particular post.

For example, to get all comments on a post, you can use the following code:

post = Post.objects.get(id=1)
comments = post.comment_set.all()

In the code above, the inverse relationship manager for all comment objects related to the object post.comment_setis returned . postBy calling .all()the method, you can get all related comment objects.

You can also use other query methods on the inverse relationship manager, such as .filter(), , .exclude()etc., to achieve more specific queries.

Guess you like

Origin blog.csdn.net/wenhao_ir/article/details/131668597