Django的models中on_delete参数详解

yipeiwu_com7年前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实现从字典中删除元素的方法

本文实例讲述了python实现从字典中删除元素的方法。分享给大家供大家参考。具体分析如下: python的字典可以通过del方法进行元素删除,下面的代码详细演示了这一过程 # Cre...

Python多层装饰器用法实例分析

本文实例讲述了Python多层装饰器用法。分享给大家供大家参考,具体如下: 前言 Python 的装饰器能够在不破坏函数原本结构的基础上,对函数的功能进行补充。当我们需要对一个函数补充不...

Python实现模拟时钟代码推荐

Python实现模拟时钟代码推荐 # coding=utf8 import sys, pygame, math, random from pygame.locals import *...

python装饰器初探(推荐)

一、含有一个装饰器 #encoding: utf-8 ############含有一个装饰器######### def outer(func): def inner(*args...

教你学会使用Python正则表达式

教你学会使用Python正则表达式

今天写爬虫偶然想到了初学正则表达式时候,看过一篇文章非常不错。检索一下还真的找到了。 re模块 re.search 经常用match = re.search(pat, str)的形式...