亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

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

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

在Django2.0以上的版本中,創(chuàng)建外鍵和一對(duì)一關(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)主鍵,因?yàn)閙ysql只支持主鍵作為外鍵,就算你沒顯式的創(chuàng)建主鍵,Django會(huì)給你自動(dòng)創(chuàng)建,如果你是DB-first,且沒創(chuàng)建主鍵:數(shù)據(jù)庫默認(rèn)使用隱藏字段:DB_ROW_ID作為主鍵

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

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

PROTECT: 保護(hù)模式,如果采用該選項(xiàng),刪除的時(shí)候,會(huì)拋出ProtectedError錯(cuò)誤。

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

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

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

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

相關(guān)文章

最新評(píng)論