對django2.0 關聯表的必填on_delete參數的含義解析
更新時間:2019年08月09日 09:23:55 作者:buxianghejiu
今天小編就為大家分享一篇對django2.0 關聯表的必填on_delete參數的含義解析,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
一對多(ForeignKey)
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)
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參數,否則會報異常:
TypeError: __init__() missing 1 required positional argument: 'on_delete'
因此,整理一下on_delete參數的各個值的含義:
on_delete=None, # 刪除關聯表中的數據時,當前表與其關聯的field的行為
on_delete=models.CASCADE, # 刪除關聯數據,與之關聯也刪除
on_delete=models.DO_NOTHING, # 刪除關聯數據,什么也不做
on_delete=models.PROTECT, # 刪除關聯數據,引發(fā)錯誤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. 與之關聯的值設置為可執(zhí)行對象的返回值,設置:models.SET(可執(zhí)行對象)
多對多(ManyToManyField)
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 參數,所以略過不提.
以上這篇對django2.0 關聯表的必填on_delete參數的含義解析就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
解決pygal.style的LightColorizedStyle參數問題
這篇文章主要介紹了解決pygal.style的LightColorizedStyle參數問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-07-07
查找適用于matplotlib的中文字體名稱與實際文件名對應關系的方法
這篇文章主要介紹了查找適用于matplotlib的中文字體名稱與實際文件名對應關系的方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-01-01

