与iexact一起使用时,Django get_or_create无法设置字段 [英] Django get_or_create fails to set field when used with iexact

查看:153
本文介绍了与iexact一起使用时,Django get_or_create无法设置字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在get_or_create中使用 name__iexact 以避免在用户输入的字段上重复。

I'd like to use name__iexact with get_or_create to avoid duplication on user entered fields where possible.

我的提供程序模型有一个用于get_or_create的名称字段。

My Provider model has a name field which I use in get_or_create.

查找工作正常,但是在第一次创建实例时,如下面的p1 / Timber示例(名称

The lookup works fine but when creating an instance for the first time as in the p1/Timber example below (the name

失败:

>>> p1, c1 = Provider.objects.get_or_create(name__iexact="Timber")
>>> p1, c1
(<Provider: >, True)
>>> p1.name
u''

在这里按预期工作:

>>> p2, c2 = Provider.objects.get_or_create(name="Cedar")
>>> p2.name, c2
('Cedar', True)
>>> p3, c3 = Provider.objects.get_or_create(name__iexact="Cedar")
>>> p3, c3
(<Provider: Cedar>, False)
>>> Provider.objects.get_or_create(name__iexact="cedar")
(<Provider: Cedar>, False)

__ iexact 不兼容使用 get_or_create 的创建部分,这是预期的行为(以及原因),还是我遇到了Django错误?

Is __iexact incompatible with the create portion of get_or_create, is this expected behavior (and why), or have I run into a Django bug?

推荐答案

您所看到的是正确的行为。

What you're seeing is the correct behaviour.

get_or_create 是'获取并返回与 kwargs 相匹配的对象的简写,如果不存在,则使用 defaults 。您正在查找的对象中,名称雪松 不区分大小写。该对象存在,因此将其返回。没什么,没什么。

get_or_create is shorthand for 'get and return the object matching kwargs, if it doesn't exist, create it using defaults'. Your lookup is looking for an object where name is a case-insensitive match to 'cedar'. That object exists, so it is returned. Nothing more, nothing less.

现在,如果没有匹配项,则斯特凡是正确的,您需要指定 name 默认值参数中。包含查找分隔符 __ 的所有查找都将从传递给 create()的参数中剥离。

Now if there was no match, Stéphane is right, and you would need to specify name in the defaults parameter. All lookups containing the lookup separator __ are stripped from the parameters passed to create().

这篇关于与iexact一起使用时,Django get_or_create无法设置字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆