Django2.0里model外鍵和一對一的on_delete參數


在django2.0后,定義外鍵和一對一關系的時候需要加on_delete選項,此參數為了避免兩個表里的數據不一致問題,不然會報錯:

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

 

舉例說明:

user=models.OneToOneField(User)

owner=models.ForeignKey(UserProfile)

需要改成:

user=models.OneToOneField(User,on_delete=models.CASCADE)          --在老版本這個參數(models.CASCADE)是默認值

owner=models.ForeignKey(UserProfile,on_delete=models.CASCADE)    --在老版本這個參數(models.CASCADE)是默認值

 

參數說明:

on_delete有CASCADE、PROTECT、SET_NULL、SET_DEFAULT、SET()五個可選擇的值

CASCADE:此值設置,是級聯刪除。

PROTECT:此值設置,是會報完整性錯誤。

SET_NULL:此值設置,會把外鍵設置為null,前提是允許為null。

SET_DEFAULT:此值設置,會把設置為外鍵的默認值。

SET():此值設置,會調用外面的值,可以是一個函數。

 

一般情況下使用CASCADE就可以了。

 

下面是官方文檔說明:

ForeignKey accepts other arguments that define the details of how the relation works.

ForeignKey. on_delete

When an object referenced by a ForeignKey is deleted, Django will emulate the behavior of the SQL constraint specified by the on_delete argument. For example, if you have a nullable ForeignKey and you want it to be set null when the referenced object is deleted:

user = models.ForeignKey( User, models.SET_NULL, blank=True, null=True, ) 

Deprecated since version 1.9:on_delete will become a required argument in Django 2.0. In older versions it defaults to CASCADE.

The possible values for on_delete are found in django.db.models:

  • CASCADE [source]

    Cascade deletes. Django emulates the behavior of the SQL constraint ON DELETE CASCADE and also deletes the object containing the ForeignKey.

  • PROTECT [source]

    Prevent deletion of the referenced object by raising ProtectedError, a subclass ofdjango.db.IntegrityError.

  • SET_NULL [source]

    Set the ForeignKey null; this is only possible if null is True.

  • SET_DEFAULT [source]

    Set the ForeignKey to its default value; a default for the ForeignKey must be set.

  • SET() [source]

    Set the ForeignKey to the value passed to SET(), or if a callable is passed in, the result of calling it. In most cases, passing a callable will be necessary to avoid executing queries at the time your models.py is imported:

    from django.conf import settings from django.contrib.auth import get_user_model from django.db import models def get_sentinel_user(): return get_user_model().objects.get_or_create(username='deleted')[0] class MyModel(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.SET(get_sentinel_user), ) 
  • DO_NOTHING [source]

    Take no action. If your database backend enforces referential integrity, this will cause an IntegrityError unless you manually add an SQL ON DELETE constraint to the database field.

ForeignKey. limit_choices_to

Sets a limit to the available choices for this field when this field is rendered using a ModelForm or the admin (by default, all objects in the queryset are available to choose). Either a dictionary, a Q object, or a callable returning a dictionary or Qobject can be used.

For example:

staff_member = models.ForeignKey( User, on_delete=models.CASCADE, limit_choices_to={'is_staff': True}, ) 

causes the corresponding field on the ModelForm to list only Users that have is_staff=True. This may be helpful in the Django admin.

The callable form can be helpful, for instance, when used in conjunction with the Python datetime module to limit selections by date range. For example:

def limit_pub_date_choices(): return {'pub_date__lte': datetime.date.utcnow()} limit_choices_to = limit_pub_date_choices 

If limit_choices_to is or returns a object, which is useful for complex queries, then it will only have an effect on the choices available in the admin when the field is not listed in raw_id_fields in the ModelAdmin for the model.

Note

If a callable is used for limit_choices_to, it will be invoked every time a new form is instantiated. It may also be invoked when a model is validated, for example by management commands or the admin. The admin constructs querysets to validate its form inputs in various edge cases multiple times, so there is a possibility your callable may be invoked several times.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM