zoukankan      html  css  js  c++  java
  • Django2.0 models中的on_delete参数

    一、外键、OneToOne字段等on_delete为必须参数
      - 如下ForeignKey字段源码,to、on_delete为必须参数 to:关联的表 on_delete:当该表中的某条数据删除后,关联外键的操作 related_name:反查参数,设置后可以在被关联表中通过该字段反查外键所在表,默认:set_表名 to_field:默认主键,因为mysql只支持主键作为外键,就算你没显式的创建主键,Django会给你自动创建, 如果你是DB-first,且没创建主键:数据库默认使用隐藏字段:DB_ROW_ID作为主键
    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.
        """
        ...
    
        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):
    
    二、on_delete参数常用设置方式
     
    • 级联删除:models.CASCADE
      当关联表中的数据删除时,该外键也删除

    • 置空:models.SET_NULL
      当关联表中的数据删除时,该外键置空,当然,你的这个外键字段得允许为空,null=True

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

    #级联删除情况
    class UserToken(models):                             #级联删除,用户删除,它也删除
        user = models.OneToOneField(to='User', on_delete=models.CASCADE, to_field='id')
        token = models.CharField(max_length=128, null=True)
    
    
    #置空情况
    class Server(models.Model):
    
        server_type_choice = (
            (1, "WEB"),
            (2, "存储"),
            (3, "缓存")
        )
    
        server_type = models.IntegerField(choices=server_type_choice)
        hostname = models.CharField(max_length=32)
        port = models.IntegerField()
        business_unit = models.ForeignKey("BusinessUnit", on_delete= models.SET_NULL, null=True)
    
    
    #设置默认值
        user = models.ForeignKey("UserInfo", on_delete= models.SET_DEFAULT, default=0)
    
    • 两个不常用的

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

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

  • 相关阅读:
    C#生成唯一值的方法汇总
    WCF中可以使用SVCUtil.exe生成客户端代理类和配置文件
    C# 打开钱箱支持北洋、佳博、爱普生
    MVC使用 Elmah 日志记录组件
    C# ZXing.Net生成二维码、识别二维码、生成带Logo的二维码(一)
    C# Gma.QrCodeNet生成二维码
    支付宝支付开发——当面付条码支付和扫码支付
    微信支付四大支付模式分别有哪些区别?
    web安全测试---AppScan扫描工具
    SVN 使用学习记录
  • 原文地址:https://www.cnblogs.com/shiqi17/p/9807026.html
Copyright © 2011-2022 走看看