django2.0 關聯表的必填on_delete參數的含義

一對多(ForeignKey)python

class ForeignKey(ForeignObject):
    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):
        super().__init__(to, on_delete, from_fields=['self'], to_fields=[to_field], **kwargs)

 

一對一(OneToOneField)django

 

class OneToOneField(ForeignKey):
    def __init__(self, to, on_delete, to_field=None, **kwargs):
        kwargs['unique'] = True
        super().__init__(to, on_delete, to_field=to_field, **kwargs)

 

從上面外鍵(ForeignKey)和一對一(OneToOneField)的參數中能夠看出,都有on_delete參數,而 django 升級到2.0以後,表與表之間關聯的時候,必需要寫on_delete參數,不然會報異常:app

 

TypeError: __init__() missing 1 required positional argument: 'on_delete'

  

所以,整理一下on_delete參數的各個值的含義:ui

on_delete=None,                               # 刪除關聯表中的數據時,當前表與其關聯的field的行爲
on_delete=models.CASCADE,             # 刪除關聯數據,與之關聯也刪除
on_delete=models.DO_NOTHING,       # 刪除關聯數據,什麼也不作
on_delete=models.PROTECT,              # 刪除關聯數據,引起錯誤ProtectedError
# models.ForeignKey('關聯表', on_delete=models.SET_NULL, blank=True, null=True)
on_delete=models.SET_NULL,            # 刪除關聯數據,與之關聯的值設置爲null(前提FK字段須要設置爲可空,一對一同理)
# models.ForeignKey('關聯表', on_delete=models.SET_DEFAULT, default='默認值')
on_delete=models.SET_DEFAULT,        # 刪除關聯數據,與之關聯的值設置爲默認值(前提FK字段須要設置默認值,一對一同理)
on_delete=models.SET,                       # 刪除關聯數據,

 a. 與之關聯的值設置爲指定值,設置:models.SET(值)
 b. 與之關聯的值設置爲可執行對象的返回值,設置:models.SET(可執行對象)
                     

 

多對多(ManyToManyField)spa

class ManyToManyField(RelatedField):
    def __init__(self, to, related_name=None, related_query_name=None,
                 limit_choices_to=None, symmetrical=None, through=None,
                 through_fields=None, db_constraint=True, db_table=None,
                 swappable=True, **kwargs):
        super().__init__(**kwargs)

由於多對多(ManyToManyField)沒有 on_delete 參數,因此略過不提.對象

相關文章
相關標籤/搜索