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
ForeignKeyis deleted, Django will emulate the behavior of the SQL constraint specified by theon_deleteargument. For example, if you have a nullableForeignKeyand 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_deletewill become a required argument in Django 2.0. In older versions it defaults toCASCADE.
The possible values for on_delete are found in django.db.models:
PROTECT[source]¶-
Prevent deletion of the referenced object by raising
ProtectedError, a subclass ofdjango.db.IntegrityError.
SET_NULL[source]¶-
Set the
ForeignKeynull; this is only possible ifnullisTrue.
SET_DEFAULT[source]¶-
Set the
ForeignKeyto its default value; a default for theForeignKeymust be set.
SET()[source]¶-
Set the
ForeignKeyto the value passed toSET(), 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
IntegrityErrorunless you manually add an SQLON DELETEconstraint 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
ModelFormor the admin (by default, all objects in the queryset are available to choose). Either a dictionary, aQobject, or a callable returning a dictionary orQobject 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
ModelFormto list onlyUsersthat haveis_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
datetimemodule 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_choicesIf
limit_choices_tois or returns aQ 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 inraw_id_fieldsin theModelAdminfor 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.
Django2.0里model外键和一对一的on_delete参数的更多相关文章
- Django2.0之后使用外键时遇到 __init__() missing 1 required positional argument: 'on_delete'
1.Django2.0之后使用外键时遇到 __init__() missing 1 required positional argument: 'on_delete' 需要在外键创建时给on_dele ...
- MySQL里创建外键时错误的解决
--MySQL里创建外键时错误的解决 --------------------------------2014/04/30 在MySQL里创建外键时(Alter table xxx add const ...
- java之hibernate之基于外键的一对一单向关联映射
这篇讲解基于外键的一对一单向关联映射 1.考察如下信息,人和身份证之间是一个一对一的关系.表的设计 注意:基于外键的一对一关联的表结构和多对一的表结构是一致的,但是,外键是唯一的. 2.类的结构 Pe ...
- Django QuerySet 方法梳理 。model外键 多对多的保存
引用:https://feifeiyum.github.io/2017/03/28/python-django-queryset/ 说明 Models 层是 Django 框架中最强大的部分之一, 大 ...
- SQLAlchemy-对象关系教程ORM-一对多(外键),一对一,多对多
一:一对多 表示一对多的关系时,在子表类中通过 foreign key (外键)引用父表类,然后,在父表类中通过 relationship() 方法来引用子表的类. 在一对多的关系中建立双向的关系,这 ...
- hibernate 关系映射之 单向外键关联一对一
这里的关系指的是对象与对象之间的关系 注解方式单向关联一对一: //这个类描述的husband是一个对应一个wife的 import javax.persistence.Entity; import ...
- 「七天自制PHP框架」应用:Model外键链接
这里以行政区数据为例: 一级行政区数据范例: 二级行政区范例: 三级行政区范例: 在Model层建立三个Model class ProvinceModel extends Model{ public ...
- 【Django 2.2文档系列】Model 外键中的on_delete参数用法
场景 我们用Django的Model时,有时候需要关联外键.关联外键时,参数:on_delete的几个配置选项到底是干嘛的呢,你知道吗? 参数介绍 models.CASCADE 级联删除.Django ...
- mysql8.0遇到删除外键的错误
错误信息:Cannot drop index 'energy_type_id': needed in a foreign key constraint 创建device表的信息 CREATE TABL ...
随机推荐
- 洛谷【P2431】正妹吃月饼
二进制前置技能:https://www.cnblogs.com/AKMer/p/9698694.html 题目传送门:https://www.luogu.org/problemnew/show/P24 ...
- java多线程编程核心技术——第二章总结
第一节synchronized同步方法目录 1.1方法内的变量为线程安全的 1.2实例变量非线程安全 1.3多个对象多个锁 1.4synchronized方法与锁对象 1.5脏读 1.6synchro ...
- python中文件打开的各个标识含义
w代表清空后写入 r代表打开后追查 +代表可以写 b代表二进制写入
- HeartBleed bug
前两年的一个严重漏洞,影响很大.出现在openssl 1.0.1和1.0.2 beta(包含1.0.1f和1.0.2beta1).利用了TLS的heartbeat. 简单的说,该漏洞被归为缓冲过度读取 ...
- Java父类构造器的讲解
众所周知,对于Java中的所有类而言,它们有一个根父类,即java.lang.Object类. 对于Java中构造器执行的顺序而言,程序执行的顺序为,先执行父类的非静态代码块,然后执行父类的相应的构造 ...
- java web基础学习 Forward和Redirect区别
Forward和Redirect代表了两种请求转发方式:直接转发和间接转发.对应到代码里,分别是RequestDispatcher类的forward()方法和HttpServletRequest类的s ...
- Could not open JPA EntityManager for transaction; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: Cannot open connection
Could not open JPA EntityManager for transaction; nested exception is javax.persistence.PersistenceE ...
- Java Numbers
通常情况下,当我们与数字打交道,使用原始数据类型,如字节,如int,long,double等 例子: int i = 5000; float gpa = 13.65; byte mask = 0xaf ...
- Lua中的点、冒号与self
Lua中的点.冒号与self,它们之间的关系主要体现在函数的定义与调用上,Lua在函数定义时可以用点也可以用冒号,如: function mytable.fun(p) return p end fun ...
- [转]hadoop运行mapreduce作业无法连接0.0.0.0/0.0.0.0:10020
14/04/04 17:15:12 INFO mapreduce.Job: map 0% reduce 0% 14/04/04 17:19:42 INFO mapreduce.Job: map 4 ...