Explain in detail the corresponding operation methods of the three relationships associated with Django database model tables: OneToOneFiled() [one-to-one], ForeignKey [one-to-many], ManyToManyField() [many-to-many]

Summarize and compare three methods for understanding Django database model table association: OneToOneFiled() [one-to-one], ForeignKey [one-to-many], ManyToManyField() [many-to-many]

Before understanding this blog post, I suggest that you take a look at my previous blog post: https://blog.csdn.net/wenhao_ir/article/details/131542371 From this blog post, you can have a specific understanding of the entire specific process of association.

When performing association operations on data tables, Django provides three association operations, namely:
① Use the method models.OneToOneField() to implement one-to-one association;
② Use the method models.ForeignKey() to implement one-to-many association;
③ Use the method models.ManyToManyField() to implement many-to-many association.

00-Basic assumptions

In order to understand these three relationships, assume the following two models and four pieces of data.
Two models:
Author and Post
Four pieces of data:

author1 post1
author2 post2

01-OneToOneFiled() [one-to-one] understanding

For one-to-one association, it is easy to understand that a certain piece of data in one table can only be associated with a certain piece of data in another table.

Examples are as follows:

from django.db import models

class Author(models.Model):
    name = models.CharField(max_length=100)
    # Other fields of the Author model

    def __str__(self):
        return self.name


class Post(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    # Other fields of the Post model

    author = models.OneToOneField(Author, on_delete=models.CASCADE)

    def __str__(self):
        return self.title

In the above example, each post is associated with an author by using the method OneToOneField() in Post.

Since it is a one-to-one association, if post1 is associated with author1, then author1 cannot be associated with post2.
insert image description here
If you want to associate post1 with post2 at this point, you can do it like this:

# 解除author1与post1的关联
author1.post.delete()

# 建立author1与post2的新关联
post2 = Post(title='Another Post', content='This is another post.', author=author1)
post2.save()

Similarly, looking at it in another direction, once post1 is associated with author1, then post1 cannot be associated with author2. As shown in the figure below:
insert image description here
If you need to associate post1with author2, you need to disassociate post1with author1and then author2establish a new association with. Here is the sample code for disassociation:

# 解除post1与author1的关联
post1.author = None
post1.save()

# 建立post1与author2的新关联
post1.author = author2
post1.save()

By post1.authorsetting to None, we can disassociate post1from author1. We can then post1.authorset the setting to author2, thereby author2establishing a new association with the .

02-ForeignKey [one-to-many] understanding

For the detailed operation process of ForeignKey [one-to-many], I have written it clearly in the blog post https://blog.csdn.net/wenhao_ir/article/details/131542371 .

Here we focus on explaining what is called "one-to-many".

The sample code is as follows:

from django.db import models

# Create your models here.

class Author(models.Model):
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name


class Post(models.Model):
    title = models.CharField(max_length=200)
    content = models.TextField()
    author = models.ForeignKey(Author, on_delete=models.CASCADE)

    def __str__(self):
        return self.title

In the case of the above code, the model Post is associated with the model Author through the method ForeignKey(), Post is "many" in "one-to-many", and Author is "one" in "one-to-many".

In the case of the ForeignKey method, that is, in the case of one-to-many, when post1 and post2 are associated with author1, they can no longer be associated with author2. As shown in the figure below:
insert image description here
the red line above indicates that post1 and post2 are associated with author1. Once post1 and post2 are associated with author1, they can no longer be associated with author2. So I crossed out the two blue lines above.
That is to say, once a post is associated with an author, it can no longer be associated with other authors, but the corresponding author can still be associated with other posts. This is the so-called one-to-many relationship.

03-ManyToManyField() [many-to-many] understanding

The sample code is as follows:

from django.db import models

class Author(models.Model):
    name = models.CharField(max_length=100)
    # Other fields of the Author model

    def __str__(self):
        return self.name


class Post(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    authors = models.ManyToManyField(Author)
    # Other fields of the Post model

    def __str__(self):
        return self.title

In the above two models, the two models are associated many-to-many by the following statement:

 authors = models.ManyToManyField(Author)

In this case, after post1 is associated with author1, it can still be associated with author2, that is, there can be multiple post authors. For example, the authors of post1 here can be author1 and author2.

And multiple posts can also be associated with the same author, that is, an author can have multiple posts. For example, after post1 is associated with author1, post2 can also be associated with author2, so that author1 has post1 and post2, that is, an author can have multiple posts.

Through the above association, it is realized that a post can have multiple authors, and an author can also have multiple posts. This is called a many-to-many relationship. As shown in the figure below:
insert image description here
The following is sample code showing how to use many-to-many association:

# 创建两个Author对象
author1 = Author(name='John Doe')
author1.save()

author2 = Author(name='Jane Smith')
author2.save()

# 创建一个Post对象并将其与两个Author关联
post = Post(title='Hello World', content='This is my post.')
post.save()
post.authors.add(author1, author2)

# 访问与Post关联的Author
print(post.authors.all())  # 输出:[<Author: John Doe>, <Author: Jane Smith>]

# 访问与Author关联的Post
print(author1.post_set.all())  # 输出:[<Post: Hello World>]
print(author2.post_set.all())  # 输出:[<Post: Hello World>]

In the example above, we created two Authorobjects: author1and author2. We then create a Postobject postand associate post.authors.add()it with two Authorobjects via .

Through post.authors.all(), we can access postall objects associated with Author.

At the same time, we can also access all objects associated with and through author1.post_set.all()and .author2.post_set.all()author1author2Post

04-The important difference between "many-to-many association" and "one-to-one" and "many-to-one" in operation

From the above many-to-many association operations, we can see that the "many-to-many association" is performed after the model objects are created, while the "one-to-one" and "many-to-one" association operations specify the association relationship when the model objects are created.

Guess you like

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