1. 程式人生 > >Django2.0 models中的on_delete引數

Django2.0 models中的on_delete引數

一、外來鍵、OneToOne欄位等on_delete為必須引數

 

  • 如下ForeignKey欄位原始碼,to、on_delete為必須引數
    to:關聯的表
    on_delete:當該表中的某條資料刪除後,關聯外來鍵的操作
    related_name:反查引數,設定後可以在被關聯表中通過該欄位反查外來鍵所在表,預設:set_表名
    to_field:預設主鍵,因為mysql只支援主鍵作為外來鍵,就算你沒顯式的建立主鍵,Django會給你自動建立,
    如果你是DB-first,且沒建立主鍵:資料庫預設使用隱藏欄位:DB_ROW_ID作為主鍵
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.
    """
    ...

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

 

二、on_delete引數常用設定方式
 

  • 級聯刪除:models.CASCADE
    當關聯表中的資料刪除時,該外來鍵也刪除

  • 置空:models.SET_NULL
    當關聯表中的資料刪除時,該外來鍵置空,當然,你的這個外來鍵欄位得允許為空,null=True

  • 設定預設值:models.SET_DEFAULT
    刪除的時候,外來鍵欄位設定為預設值,所以定義外來鍵的時候注意加上一個預設值。

#級聯刪除情況
class UserToken(models):                             #級聯刪除,使用者刪除,它也刪除
    user = models.OneToOneField(to='User', on_delete=models.CASCADE, to_field='id')
    token = models.CharField(max_length=128, null=True)


#置空情況
class Server(models.Model):

    server_type_choice = (
        (1, "WEB"),
        (2, "儲存"),
        (3, "快取")
    )

    server_type = models.IntegerField(choices=server_type_choice)
    hostname = models.CharField(max_length=32)
    port = models.IntegerField()
    business_unit = models.ForeignKey("BusinessUnit", on_delete= models.SET_NULL, null=True)


#設定預設值
    user = models.ForeignKey("UserInfo", on_delete= models.SET_DEFAULT, default=0)
  • 兩個不常用的

  • PROTECT: 保護模式,如果採用該選項,刪除的時候,會丟擲ProtectedError錯誤。

  • SET(): 自定義一個值,該值當然只能是對應的實體了