Django的models中on_delete参数详解

yipeiwu_com6年前Python基础

在Django2.0以上的版本中,创建外键和一对一关系必须定义on_delete参数,我们可以在其源码中看到相关信息

class ForeignKey(ForeignObject):
  """
  Provide a many-to-one relation by adding a column to the local model
  to hold the remote value.

  By default ForeignKey will target the pk of the remote model but this
  behavior can be changed by using the ``to_field`` argument.
  """

  # Field flags
  many_to_many = False
  many_to_one = True
  one_to_many = False
  one_to_one = False

  rel_class = ManyToOneRel

  empty_strings_allowed = False
  default_error_messages = {
    'invalid': _('%(model)s instance with %(field)s %(value)r does not exist.')
  }
  description = _("Foreign Key (type determined by related field)")

  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):

  • to:关联的表
  • on_delete:当该表中的某条数据删除后,关联外键的操作
  • related_name:反查参数,设置后可以在被关联表中通过该字段反查外键所在表,默认:set_表名
  • to_field:默认主键,因为mysql只支持主键作为外键,就算你没显式的创建主键,Django会给你自动创建,如果你是DB-first,且没创建主键:数据库默认使用隐藏字段:DB_ROW_ID作为主键

on_delete参数设置

CASCADE:级联删除,当关联表中的数据删除时,该外键也删除

PROTECT: 保护模式,如果采用该选项,删除的时候,会抛出ProtectedError错误。

SET_NULL: 置空模式,删除的时候,外键字段被设置为空,前提就是blank=True, null=True,定义该字段的时候,允许为空。

SET_DEFAULT: 设置默认值,删除的时候,外键字段设置为默认值,所以定义外键的时候注意加上一个默认值。

SET(): 自定义一个值,该值当然只能是对应的实体

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python cx_Oracle模块的安装和使用详细介绍

python cx_Oracle模块的安装 最近需要写一个数据迁移脚本,将单一Oracle中的数据迁移到MySQL Sharding集群,在linux下安装cx_Oracle感觉还是有一...

python 读取.csv文件数据到数组(矩阵)的实例讲解

利用numpy库 (缺点:有缺失值就无法读取) 读: import numpy my_matrix = numpy.loadtxt(open("1.csv","rb"),delim...

python实现逆序输出一个数字的示例讲解

问题是:输入一个数字,按照指定要求逆序输出该数字,很简单,下面是实现: #!usr/bin/env python #encoding:utf-8 ''' __Author__:沂水...

Python 修改列表中的元素方法

Python 修改列表中的元素方法

如下所示: #打印列表文件 def show_magicians(magics) : for magic in magics : print(magic) #修改列表文件...

解决python3 网络请求路径包含中文的问题

在爬一个网站的时候,端点包含中文浏览器是可以自动解决这个转换的,在代码中就需要处理一下了。 请求过程的异常如下: self._output(request.encode('ascii...