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

转载于:https://www.cnblogs.com/shiqi17/p/9807026.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值