在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 Q 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.

Django2.0里model外键和一对一的on_delete参数的更多相关文章

  1. Django2.0之后使用外键时遇到 __init__() missing 1 required positional argument: 'on_delete'

    1.Django2.0之后使用外键时遇到 __init__() missing 1 required positional argument: 'on_delete' 需要在外键创建时给on_dele ...

  2. MySQL里创建外键时错误的解决

    --MySQL里创建外键时错误的解决 --------------------------------2014/04/30 在MySQL里创建外键时(Alter table xxx add const ...

  3. java之hibernate之基于外键的一对一单向关联映射

    这篇讲解基于外键的一对一单向关联映射 1.考察如下信息,人和身份证之间是一个一对一的关系.表的设计 注意:基于外键的一对一关联的表结构和多对一的表结构是一致的,但是,外键是唯一的. 2.类的结构 Pe ...

  4. Django QuerySet 方法梳理 。model外键 多对多的保存

    引用:https://feifeiyum.github.io/2017/03/28/python-django-queryset/ 说明 Models 层是 Django 框架中最强大的部分之一, 大 ...

  5. SQLAlchemy-对象关系教程ORM-一对多(外键),一对一,多对多

    一:一对多 表示一对多的关系时,在子表类中通过 foreign key (外键)引用父表类,然后,在父表类中通过 relationship() 方法来引用子表的类. 在一对多的关系中建立双向的关系,这 ...

  6. hibernate 关系映射之 单向外键关联一对一

    这里的关系指的是对象与对象之间的关系 注解方式单向关联一对一: //这个类描述的husband是一个对应一个wife的 import javax.persistence.Entity; import ...

  7. 「七天自制PHP框架」应用:Model外键链接

    这里以行政区数据为例: 一级行政区数据范例: 二级行政区范例: 三级行政区范例: 在Model层建立三个Model class ProvinceModel extends Model{ public ...

  8. 【Django 2.2文档系列】Model 外键中的on_delete参数用法

    场景 我们用Django的Model时,有时候需要关联外键.关联外键时,参数:on_delete的几个配置选项到底是干嘛的呢,你知道吗? 参数介绍 models.CASCADE 级联删除.Django ...

  9. mysql8.0遇到删除外键的错误

    错误信息:Cannot drop index 'energy_type_id': needed in a foreign key constraint 创建device表的信息 CREATE TABL ...

随机推荐

  1. 白话算法(6) 散列表(Hash Table)从理论到实用(中)

    不用链接法,还有别的方法能处理碰撞吗?扪心自问,我不敢问这个问题.链接法如此的自然.直接,以至于我不敢相信还有别的(甚至是更好的)方法.推动科技进步的人,永远是那些敢于问出比外行更天真.更外行的问题, ...

  2. Hive安装配置要点

    官网下载安装包: 在Profile下面定义HIVE_HOME以及HADOOP_HOME,然后在PATH下面添加HOME/bin目录,用于在命令行直接敲beeline,hive即可执行命令: 需要在ha ...

  3. Android中EditTex焦点设置和弹不弹出输入法的问题(转)

    今天编程碰到了一个问题:有一款平板,打开一个有EditText的Activity会默认弹出输入法.为了解决这个问题就深入研究了下android中焦点Focus和弹出输入法的问题.在网上看了些例子都不够 ...

  4. stm32与三菱PLC通信

    一.三菱PLC通讯概要   三菱PLC FX系列通信结构如下图所示: 三菱PLC FX系列的通信规格如下图所示: 三菱PLC FX系列一般有以下几种通信模块,以FX2N为例: FX2N-232-BD ...

  5. shell入门-sed-1

    sed这个工具比grep复杂一点,功能比grep复杂一点 功能也能指定匹配的行,不能颜色显示 sed 基础功能 [root@wangshaojun ~]# sed -n '10'p 1.txtuucp ...

  6. Flask16 项目结构、flask_script插件

    1 项目结构 需求:易维护.可扩展 1.1 views 处理逻辑和路由映射 C 1.2 models 模型类 M 1.3 templates 模板文件 V 1.4 static 今天文件,如:js.c ...

  7. BSGS(大小步)算法

    BSGS算法主要用于求解形如ax≡b(mod p)的式子中x的值. 在这里我们不妨设 x=k1*n-k2 这时我们就可以将式子转化为 ak1*n≡b*ak2(mod p) 这里的n我们设为√p,所以我 ...

  8. Haskell语言为什么值得你去学习

    摘自http://www.vaikan.com/why-haskell-is-worth-learning/ Haskell语言为什么值得你去学习 当我向一些新手推荐学习Haskell语言时,得到的反 ...

  9. JDK1.8的安装与卸载

    Java的下载地址: https://www.java.com/zh_CN/download/ 下载完成后打开进入界面: 点击下一步, 上面也无需更改,也可自定义设置安装路径, 再次确认安装路径,点击 ...

  10. SQL笔记:中级篇

    1.LIMIT 查询前多少条数据 例如:查询user表前三条数据 SELECT * FROM  user LIMIT 3 ORACLE:  SELECT name FROM user WHERE RO ...