django 2.0外键处理

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就可以了。


下面是官方文档说明:

ForeignKeyaccepts other arguments that define the details of how the relation works.

ForeignKey.on_delete

When an object referenced by aForeignKeyis 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 foron_deleteare found indjango.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 raisingProtectedError, a subclass ofdjango.db.IntegrityError.

SET_NULL[source]

Set theForeignKeynull; this is only possible ifnullisTrue.

SET_DEFAULT[source]

Set theForeignKeyto its default value; a default for theForeignKeymust be set.

SET()[source]

Set theForeignKeyto 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:

fromdjango.confimportsettingsfromdjango.contrib.authimportget_user_modelfromdjango.dbimportmodelsdefget_sentinel_user():returnget_user_model().objects.get_or_create(username='deleted')[0]classMyModel(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 anIntegrityErrorunless you manually add an SQLONDELETEconstraint to the database field.

ForeignKey.limit_choices_to

Sets a limit to the available choices for this field when this field is rendered using aModelFormor 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 theModelFormto 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 Pythondatetimemodule to limit selections by date range. For example:

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

Iflimit_choices_tois or returns aQobject, which is useful forcomplex 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 forlimit_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.

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,242评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,769评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,484评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,133评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,007评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,080评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,496评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,190评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,464评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,549评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,330评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,205评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,567评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,889评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,160评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,475评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,650评论 2 335

推荐阅读更多精彩内容

  • 假如你结婚了,假如你是个男人,请给自己的老婆看,或许可以有深远的影响! 如果你结婚了,你是个女人,更应该好好看看,...
    SJL四姐阅读 688评论 0 0
  • 最近主要在研究 iOS 中的 JS 这一块内容,本文打算从 为什么不能单纯地搞前端、JSCore 的原理和通信机制...
    萧城x阅读 4,938评论 0 11
  • (void)viewDidLoad {[super viewDidLoad];CAShapeLayer *circ...
    baiwulong阅读 1,003评论 0 0