Django数据模型中on_delete使用详解


Posted in Python onNovember 30, 2020

on_delete属性针对外键ForeignKey

一、django3.0官方文档介绍:

Many-to-one relationships多对一关系

To define a many-to-one relationship, use django.db.models.ForeignKey. You use it just like any other Field type: by including it as a class attribute of your model.

ForeignKey requires a positional argument: the class to which the model is related.

For example, if a Car model has a Manufacturer ? that is, a Manufacturer makes multiple cars but each Car only has one Manufacturer ? use the following definitions:

from django.db import models

class Manufacturer(models.Model):
  # ...
  pass

class Car(models.Model):
  manufacturer = models.ForeignKey(Manufacturer, on_delete=models.CASCADE)
  # ...

 You can also create recursive relationships (an object with a many-to-one relationship to itself) and relationships to models not yet defined; see the model field reference for details.

It's suggested, but not required, that the name of a ForeignKey field (manufacturer in the example above) be the name of the model, lowercase. You can, of course, call the field whatever you want.

常见的使用方式(设置为null)

class ApiList(models.Model):
 desc = models.CharField(max_length=255, verbose_name="接口描述")
 keyword = models.CharField(max_length=100, verbose_name="请求关键字")
 response = models.TextField(verbose_name="响应结果")
 api = models.ForeignKey(Api, blank=True, null=True, on_delete=models.SET_NULL, verbose_name="所属接口")
 status = models.IntegerField(default=1, verbose_name="状态")
 create_at = models.CharField(max_length=20, verbose_name="创建时间")
 update_at = models.CharField(max_length=20, verbose_name="更新时间")

一对多(ForeignKey)

class ForeignKey(ForeignObject):
  def __init__(self, to, on_delete, related_name=None, related_query_name=None,
         limit_choices_to=None, parent_link=False, to_field=None,
         db_constraint=True, **kwargs):
    super().__init__(to, on_delete, from_fields=['self'], to_fields=[to_field], **kwargs)

一对一(OneToOneField)

class OneToOneField(ForeignKey):
  def __init__(self, to, on_delete, to_field=None, **kwargs):
    kwargs['unique'] = True
    super().__init__(to, on_delete, to_field=to_field, **kwargs)

从上面外键(ForeignKey)和一对一(OneToOneField)的参数中可以看出,都有on_delete参数,而 django 升级到2.0之后,表与表之间关联的时候,必须要写on_delete参数,否则会报异常:

TypeError: __init__() missing 1 required positional argument: 'on_delete'

因此,整理一下on_delete参数的各个值的含义:

on_delete=None,        # 删除关联表中的数据时,当前表与其关联的field的行为
on_delete=models.CASCADE,   # 删除关联数据,与之关联也删除
on_delete=models.DO_NOTHING, # 删除关联数据,什么也不做
on_delete=models.PROTECT,   # 删除关联数据,引发错误ProtectedError
# models.ForeignKey('关联表', on_delete=models.SET_NULL, blank=True, null=True)
on_delete=models.SET_NULL,  # 删除关联数据,与之关联的值设置为null(前提FK字段需要设置为可空,一对一同理)
# models.ForeignKey('关联表', on_delete=models.SET_DEFAULT, default='默认值')
on_delete=models.SET_DEFAULT, # 删除关联数据,与之关联的值设置为默认值(前提FK字段需要设置默认值,一对一同理)
on_delete=models.SET,     # 删除关联数据,
 a. 与之关联的值设置为指定值,设置:models.SET(值)
 b. 与之关联的值设置为可执行对象的返回值,设置:models.SET(可执行对象)

多对多(ManyToManyField)

class ManyToManyField(RelatedField):
  def __init__(self, to, related_name=None, related_query_name=None,
         limit_choices_to=None, symmetrical=None, through=None,
         through_fields=None, db_constraint=True, db_table=None,
         swappable=True, **kwargs):
    super().__init__(**kwargs)

因为多对多(ManyToManyField)没有 on_delete 参数,所以略过不提. 

二、on_delete外键删除方式

  1. CASCADE:级联删除。当Manufacturer对象删除时,它对应的Car对象也会删除。
  2. PROTECT:保护模式,采用该选项,删除时会抛出ProtectedError错误。
  3. SET_NULL:置空模式,删除的时候,外键字段被设置为空,前提就是blank=True, null=True,定义该字段的时候,允许为空。当Manufacturer对象删除时,它对应的Car对象的manufacturer字段会置空,前提是null=True
  4. SET_DEFAULT:置默认值,删除的时候,外键字段设置为默认值,所以定义外键的时候注意加上一个默认值。
  5. SET():自定义一个值,该值当然只能是对应的实体了

django3.0关于models官方文档地址:
1.https://docs.djangoproject.com/en/3.0/topics/db/models/
2.https://docs.djangoproject.com/en/3.0/ref/models/fields/#django.db.models.ForeignKey

到此这篇关于Django数据模型中on_delete使用详解的文章就介绍到这了,更多相关Django on_delete使用内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
python查询sqlite数据表的方法
May 08 Python
Python合并字符串的3种方法
May 21 Python
在Django框架中运行Python应用全攻略
Jul 17 Python
Python的requests网络编程包使用教程
Jul 11 Python
Python使用matplotlib绘制随机漫步图
Aug 27 Python
python实现本地批量ping多个IP的方法示例
Aug 07 Python
python设置代理和添加镜像源的方法
Feb 14 Python
屏蔽Django admin界面添加按钮的操作
Mar 11 Python
Python爬虫之Selenium鼠标事件的实现
Dec 04 Python
python实现图像随机裁剪的示例代码
Dec 10 Python
用Python实现定时备份Mongodb数据并上传到FTP服务器
Jan 27 Python
python数字图像处理之对比度与亮度调整示例
Jun 28 Python
Django数据统计功能count()的使用
Nov 30 #Python
Python常用断言函数实例汇总
Nov 30 #Python
在pycharm中使用pipenv创建虚拟环境和安装django的详细教程
Nov 30 #Python
Django 用户认证Auth组件的使用
Nov 30 #Python
python tqdm库的使用
Nov 30 #Python
Python+unittest+DDT实现数据驱动测试
Nov 30 #Python
Python logging自定义字段输出及打印颜色
Nov 30 #Python
You might like
2020年4月放送!《Princess Connect Re:Dive》制作组 & 角色声优公开!
2020/03/06 日漫
浅析php中如何在有限的内存中读取大文件
2013/07/02 PHP
PHP文件去掉PHP注释空格的函数分析(PHP代码压缩)
2013/07/02 PHP
使用phpQuery采集网页的方法
2013/11/13 PHP
PHP内置过滤器FILTER使用实例
2014/06/25 PHP
JavaScript 克隆数组最简单的方法
2009/02/12 Javascript
div失去焦点事件实现思路
2014/04/22 Javascript
JavaScript实现生成GUID(全局统一标识符)
2014/09/05 Javascript
jquery 构造函数在表单提交过程中修改数据
2015/05/25 Javascript
简单实现限制uploadify上传个数
2015/11/16 Javascript
JavaScript中循环遍历Array与Map的方法小结
2016/03/12 Javascript
JS监听微信、支付宝等移动app及浏览器的返回、后退、上一页按钮的事件方法
2016/08/05 Javascript
Web安全测试之XSS实例讲解
2016/08/15 Javascript
原生node.js案例--前后台交互
2017/02/20 Javascript
vue-router项目实战总结篇
2018/02/11 Javascript
javascript定时器的简单应用示例【控制方块移动】
2019/06/17 Javascript
微信小程序实现收货地址左滑删除
2020/11/18 Javascript
layui禁用侧边导航栏点击事件的解决方法
2019/09/25 Javascript
vue实现折线图 可按时间查询
2020/08/21 Javascript
.netcore+vue 实现压缩文件下载功能
2020/09/24 Javascript
[01:20:37]FNATIC vs NIP 2019国际邀请赛小组赛 BO2 第一场 8.16
2019/08/19 DOTA
Python笔记(叁)继续学习
2012/10/24 Python
Python实现的检测网站挂马程序
2014/11/30 Python
python 自动化将markdown文件转成html文件的方法
2016/09/23 Python
python3实现抓取网页资源的 N 种方法
2017/05/02 Python
用Python将结果保存为xlsx的方法
2019/01/28 Python
Pycharm最新激活码2019(推荐)
2019/12/31 Python
Python解析多帧dicom数据详解
2020/01/13 Python
Python递归求出列表(包括列表中的子列表)的最大值实例
2020/02/27 Python
Python 列表推导式需要注意的地方
2020/10/23 Python
CSS3的first-child选择器实战攻略
2016/04/28 HTML / CSS
英国PC组件和在线电脑商店:SCAN
2019/04/18 全球购物
中专生学习生活的自我评价分享
2013/10/27 职场文书
见习期自我鉴定范文
2014/03/19 职场文书
圣诞晚会主持词
2015/07/01 职场文书
攻击最高的10只幽灵系神奇宝贝,坚盾剑怪排第一,第五最为可怕
2022/03/18 日漫