一、外鍵、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(): 自定義一個值,該值當然只能是對應的實體了