Django的models中on_delete參數詳解
在Django2.0以上的版本中,創(chuàng)建外鍵和一對一關系必須定義on_delete參數,我們可以在其源碼中看到相關信息
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:關聯(lián)的表
- on_delete:當該表中的某條數據刪除后,關聯(lián)外鍵的操作
- related_name:反查參數,設置后可以在被關聯(lián)表中通過該字段反查外鍵所在表,默認:set_表名
- to_field:默認主鍵,因為mysql只支持主鍵作為外鍵,就算你沒顯式的創(chuàng)建主鍵,Django會給你自動創(chuàng)建,如果你是DB-first,且沒創(chuàng)建主鍵:數據庫默認使用隱藏字段:DB_ROW_ID作為主鍵
on_delete參數設置
CASCADE:級聯(lián)刪除,當關聯(lián)表中的數據刪除時,該外鍵也刪除
PROTECT: 保護模式,如果采用該選項,刪除的時候,會拋出ProtectedError錯誤。
SET_NULL: 置空模式,刪除的時候,外鍵字段被設置為空,前提就是blank=True, null=True,定義該字段的時候,允許為空。
SET_DEFAULT: 設置默認值,刪除的時候,外鍵字段設置為默認值,所以定義外鍵的時候注意加上一個默認值。
SET(): 自定義一個值,該值當然只能是對應的實體
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
tensorflow 實現(xiàn)自定義梯度反向傳播代碼
今天小編就為大家分享一篇tensorflow 實現(xiàn)自定義梯度反向傳播代碼,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-02-02對變量賦值的理解--Pyton中讓兩個值互換的實現(xiàn)方法
下面小編就為大家分享一篇Pyton中讓兩個值互換的實現(xiàn)方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2017-11-11