欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Django的models中on_delete參數(shù)詳解

 更新時間:2019年07月16日 08:33:08   作者:lemon  
這篇文章主要介紹了Django的models中on_delete參數(shù)詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

在Django2.0以上的版本中,創(chuàng)建外鍵和一對一關(guān)系必須定義on_delete參數(shù),我們可以在其源碼中看到相關(guān)信息

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.
  """

  # Field flags
  many_to_many = False
  many_to_one = True
  one_to_many = False
  one_to_one = False

  rel_class = ManyToOneRel

  empty_strings_allowed = False
  default_error_messages = {
    'invalid': _('%(model)s instance with %(field)s %(value)r does not exist.')
  }
  description = _("Foreign Key (type determined by related field)")

  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):

  • to:關(guān)聯(lián)的表
  • on_delete:當(dāng)該表中的某條數(shù)據(jù)刪除后,關(guān)聯(lián)外鍵的操作
  • related_name:反查參數(shù),設(shè)置后可以在被關(guān)聯(lián)表中通過該字段反查外鍵所在表,默認(rèn):set_表名
  • to_field:默認(rèn)主鍵,因為mysql只支持主鍵作為外鍵,就算你沒顯式的創(chuàng)建主鍵,Django會給你自動創(chuàng)建,如果你是DB-first,且沒創(chuàng)建主鍵:數(shù)據(jù)庫默認(rèn)使用隱藏字段:DB_ROW_ID作為主鍵

on_delete參數(shù)設(shè)置

CASCADE:級聯(lián)刪除,當(dāng)關(guān)聯(lián)表中的數(shù)據(jù)刪除時,該外鍵也刪除

PROTECT: 保護(hù)模式,如果采用該選項,刪除的時候,會拋出ProtectedError錯誤。

SET_NULL: 置空模式,刪除的時候,外鍵字段被設(shè)置為空,前提就是blank=True, null=True,定義該字段的時候,允許為空。

SET_DEFAULT: 設(shè)置默認(rèn)值,刪除的時候,外鍵字段設(shè)置為默認(rèn)值,所以定義外鍵的時候注意加上一個默認(rèn)值。

SET(): 自定義一個值,該值當(dāng)然只能是對應(yīng)的實體

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論