溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

django2.0關(guān)聯(lián)表中必填on_delete參數(shù)的含義是什么

發(fā)布時間:2021-09-09 09:25:09 來源:億速云 閱讀:251 作者:小新 欄目:開發(fā)技術(shù)

這篇文章主要介紹django2.0關(guān)聯(lián)表中必填on_delete參數(shù)的含義是什么,文中介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們一定要看完!

一對多(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)的參數(shù)中可以看出,都有on_delete參數(shù),而 django 升級到2.0之后,表與表之間關(guān)聯(lián)的時候,必須要寫on_delete參數(shù),否則會報異常:

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

因此,整理一下on_delete參數(shù)的各個值的含義:

on_delete=None,        # 刪除關(guān)聯(lián)表中的數(shù)據(jù)時,當(dāng)前表與其關(guān)聯(lián)的field的行為
on_delete=models.CASCADE,   # 刪除關(guān)聯(lián)數(shù)據(jù),與之關(guān)聯(lián)也刪除
on_delete=models.DO_NOTHING, # 刪除關(guān)聯(lián)數(shù)據(jù),什么也不做
on_delete=models.PROTECT,   # 刪除關(guān)聯(lián)數(shù)據(jù),引發(fā)錯誤ProtectedError
# models.ForeignKey('關(guān)聯(lián)表', on_delete=models.SET_NULL, blank=True, null=True)
on_delete=models.SET_NULL,  # 刪除關(guān)聯(lián)數(shù)據(jù),與之關(guān)聯(lián)的值設(shè)置為null(前提FK字段需要設(shè)置為可空,一對一同理)
# models.ForeignKey('關(guān)聯(lián)表', on_delete=models.SET_DEFAULT, default='默認(rèn)值')
on_delete=models.SET_DEFAULT, # 刪除關(guān)聯(lián)數(shù)據(jù),與之關(guān)聯(lián)的值設(shè)置為默認(rèn)值(前提FK字段需要設(shè)置默認(rèn)值,一對一同理)
on_delete=models.SET,     # 刪除關(guān)聯(lián)數(shù)據(jù),
 a. 與之關(guān)聯(lián)的值設(shè)置為指定值,設(shè)置:models.SET(值)
 b. 與之關(guān)聯(lián)的值設(shè)置為可執(zhí)行對象的返回值,設(shè)置: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 參數(shù),所以略過不提.

以上是“django2.0關(guān)聯(lián)表中必填on_delete參數(shù)的含義是什么”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI