标签:tar _id class default 级联 protect sql lse any
?
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):
?
级联删除: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(): 自定义一个值,该值当然只能是对应的实体了
标签:tar _id class default 级联 protect sql lse any
原文地址:https://www.cnblogs.com/shiqi17/p/9807026.html