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(): 自定义一个值,该值当然只能是对应的实体了

  • 相关阅读:
    社会影响力入门:打造有所作为的公司
    JSP中的include有哪些?有什么差别?
    关于程序猿怎样降低程序Bug的若干建议
    linux文件打开模式
    IntelliJ IDEA 问题总结之中的一个 —— jar包、assets、maven、git
    linux下改动内核參数进行Tcp性能调优 -- 高并发
    思科模拟器配置三层交换机局域网
    MFC调试小技巧
    JAVA基础编程50题(10-12题)具体解释
    加速度传感器的原理和应用-手机翻转、失重检测、运动检测、位置识别
  • 原文地址:https://www.cnblogs.com/shiqi17/p/9807026.html
Copyright © 2011-2022 走看看