1. 程式人生 > 程式設計 >Django資料模型中on_delete使用詳解

Django資料模型中on_delete使用詳解

on_delete屬性針對外來鍵ForeignKey

一、django3.0官方文件介紹:

Many-to-one relationships多對一關係

To define a many-to-one relationship,use django.db.models.ForeignKey. You use it just like any other Field type: by including it as a class attribute of your model.

ForeignKey requires a positional argument: the class to which the model is related.

For example,if a Car model has a Manufacturer – that is,a Manufacturer makes multiple cars but each Car only has one Manufacturer – use the following definitions:

from django.db import models

class Manufacturer(models.Model):
  # ...
  pass

class Car(models.Model):
  manufacturer = models.ForeignKey(Manufacturer,on_delete=models.CASCADE)
  # ...

You can also create recursive relationships (an object with a many-to-one relationship to itself) and relationships to models not yet defined; see the model field reference for details.

It's suggested,but not required,that the name of a ForeignKey field (manufacturer in the example above) be the name of the model,lowercase. You can,of course,call the field whatever you want.

常見的使用方式(設定為null)

class ApiList(models.Model):
 desc = models.CharField(max_length=255,verbose_name="介面描述")
 keyword = models.CharField(max_length=100,verbose_name="請求關鍵字")
 response = models.TextField(verbose_name="響應結果")
 api = models.ForeignKey(Api,blank=True,null=True,on_delete=models.SET_NULL,verbose_name="所屬介面")
 status = models.IntegerField(default=1,verbose_name="狀態")
 create_at = models.CharField(max_length=20,verbose_name="建立時間")
 update_at = models.CharField(max_length=20,verbose_name="更新時間")

class ForeignKey(ForeignObject):
  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):
    super().__init__(to,from_fields=['self'],to_fields=[to_field],**kwargs)

一對一(OneToOneField)

class OneToOneField(ForeignKey):
  def __init__(self,**kwargs):
    kwargs['unique'] = True
    super().__init__(to,to_field=to_field,**kwargs)

從上面外來鍵(ForeignKey)和一對一(OneToOneField)的引數中可以看出,都有on_delete引數,而 django 升級到2.0之後,表與表之間關聯的時候,必須要寫on_delete引數,否則會報異常:

TypeError: __init__() missing 1 required positional argument: 'on_delete'

因此,整理一下on_delete引數的各個值的含義:

on_delete=None,# 刪除關聯表中的資料時,當前表與其關聯的field的行為
on_delete=models.CASCADE,# 刪除關聯資料,與之關聯也刪除
on_delete=models.DO_NOTHING,什麼也不做
on_delete=models.PROTECT,引發錯誤ProtectedError
# models.ForeignKey('關聯表',null=True)
on_delete=models.SET_NULL,與之關聯的值設定為null(前提FK欄位需要設定為可空,一對一同理)
# models.ForeignKey('關聯表',on_delete=models.SET_DEFAULT,default='預設值')
on_delete=models.SET_DEFAULT,與之關聯的值設定為預設值(前提FK欄位需要設定預設值,一對一同理)
on_delete=models.SET,a. 與之關聯的值設定為指定值,設定:models.SET(值)
 b. 與之關聯的值設定為可執行物件的返回值,設定:models.SET(可執行物件)

多對多(ManyToManyField)

class ManyToManyField(RelatedField):
  def __init__(self,symmetrical=None,through=None,through_fields=None,db_table=None,swappable=True,**kwargs):
    super().__init__(**kwargs)

因為多對多(ManyToManyField)沒有 on_delete 引數,所以略過不提.

二、on_delete外來鍵刪除方式

  1. CASCADE:級聯刪除。當Manufacturer物件刪除時,它對應的Car物件也會刪除。
  2. PROTECT:保護模式,採用該選項,刪除時會丟擲ProtectedError錯誤。
  3. SET_NULL:置空模式,刪除的時候,外來鍵欄位被設定為空,前提就是blank=True,定義該欄位的時候,允許為空。當Manufacturer物件刪除時,它對應的Car物件的manufacturer欄位會置空,前提是null=True
  4. SET_DEFAULT:置預設值,刪除的時候,外來鍵欄位設定為預設值,所以定義外來鍵的時候注意加上一個預設值。
  5. SET():自定義一個值,該值當然只能是對應的實體了

django3.0關於models官方文件地址:
1.https://docs.djangoproject.com/en/3.0/topics/db/models/
2.https://docs.djangoproject.com/en/3.0/ref/models/fields/#django.db.models.ForeignKey

到此這篇關於Django資料模型中on_delete使用詳解的文章就介紹到這了,更多相關Django on_delete使用內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!