对django2.0 关联表的必填on_delete参数的含义解析

yipeiwu_com5年前Python基础

一对多(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 参数,所以略过不提.

以上这篇对django2.0 关联表的必填on_delete参数的含义解析就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python基于Matplotlib库简单绘制折线图的方法示例

Python基于Matplotlib库简单绘制折线图的方法示例

本文实例讲述了Python基于Matplotlib库简单绘制折线图的方法。分享给大家供大家参考,具体如下: Matplotlib画折线图,有一些离散点,想看看这些点的变动趋势: im...

python3.7将代码打包成exe程序并添加图标的方法

python3.7将代码打包成exe程序并添加图标的方法

1、环境 1、python 3.7 2、pyinstaller 2、下载方式: 2.1 python安装(略) 2.2 安装pyinstaller 打开DOS窗口输入以下命令:...

python模仿网页版微信发送消息功能

python模仿网页版微信发送消息功能

这个微信版网页版虽然繁琐,但是不是很难,全程不带加密的。有兴趣的可以试着玩一玩,如果有兴趣的话,可以完善一下,做一些比较有意思的东西。 开发环境:Windows10 开发语言:Pytho...

Python模块文件结构代码详解

本文研究的主要是Python模块文件结构的相关内容,具体如下。 Python文件结构 文件结构(范例全文) #/usr/bin/env python "this is a...

Python连接Redis的基本配置方法

在Linux系统下Python连接Redis的基本配置方法具体操作步骤 系统环境: OS:Oracle Linux Enterprise 5.6 Redis:redis-2.6.8 Py...