Django-orm many-to-many addition, deletion, modification and query


Step 1: Create a blog application

博客(blog)Create an app in any project to practice Django中多对多关系using.

python manage.py startapp blog

Register in the setting after creation blog应用, otherwise there 模型迁移will be errors.

INSTALLED_APPS = [
	......
	'blog'
]

After creating the application, draw a simple ER diagram to see where the many-to-many relationship is used in the blog project, 一个用户可以收藏多篇文章, 一篇文章可以被多个用户收藏.
ER Diagram for Users and Articles

In ordinary projects, the generally passed 中间表form is 两个或多个模型between 建立多对多关联关系, and in Django projects 多对多关联字段, the model is established by adding model classes 多对多关联关系.

Step 2: Write the models.py model file

models.ManyToManyField(to)This api is mainly used , and tothe parameters are used to specify 关联类型. Let's write the blogapplication models.pyfile below.

from django.db import models

class Article(models.Model):
    title = models.CharField(max_length=100, verbose_name='文章标题')

    class Meta:
        db_table = 'article'
        verbose_name = '文章'

# 因为在博客项目中, 每个用户都是作者, 所以这里用author来表示用户
class Author(models.Model):
    username = models.CharField(max_length=30, verbose_name='用户名')
    articles_collected = models.ManyToManyField(to=Article, verbose_name='收藏的文章')

    class Meta:
        db_table = 'author'
        verbose_name = '作者'

Execute makemigrationsand migratetest the model 迁移.

python manage.py makemigrations blog
python manage.py migrate blog

After generation, look at the effect in the figure below, and you can see that the fields 作者模型类defined in articles_collecteddid not appear in 作者表, but a table named table was automatically generated 模型类名小写_关联字段, in which two models were stored id.
insert image description here

Step 3: Use orm to perform many-to-many addition, deletion, modification and query operations

Enter in the console 以下命令to enter Django shell交互环境for testing.

python manage.py shell

After entering shell环境, the blog应用importedmodels模块

from blog.models import *

Add relationship

# 创建一个用户
author = Author.objects.create(username='张三')
# 创建两篇文章
article1 = Article.objects.create(title='小红帽')
article2 = Article.objects.create(title='大灰狼')

# 对象.关联字段.add()方法用来添加关联关系
author.articles_collected.add(1)  # 可以是文章的id
author.articles_collected.add(article2) # 也可以是对应的文章对象

Check the effect, you can see that both methods can be added successfully.
insert image description here

Query all related objects by related fields

对象.关联字段.all()Used to query all associated objects.

author.articles_collected.all()

QuerySetContains two articles in the author's collection.
insert image description here

remove affiliation

对象.关联字段.remove()Used to remove the relationship, and add()the same can also be used idor 对象as a parameter.

author.articles_collected.remove(1)
author.articles_collected.remove(article2)

After the execution, re-query the articles saved by the user, and you can see that the two articles in the favorites have been removed.
insert image description here

update relationship

对象.关联字段.set()It can be used to 添加 修改 清空operate, receiving one 列表as a parameter, which can be 文章对象or can be in the list 文章id.

author.articles_collected.set([article1,2])

insert image description here
Every call set()is made 修改操作.

author.articles_collected.set([2])

insert image description here
If the argument is one 空列表, then 清空关联关系.

author.articles_collected.set([])

insert image description here

Summarize

add()Applicable to the 原有基础above 添加association relationship from which
remove() an association relationship is used to associate the relationship, which can be used to perform当前关联关系移除
set()设置修改操作

Guess you like

Origin blog.csdn.net/qq_45458749/article/details/125035096