django ORM中update_or_create功能,如果只要匹配某一特定字段呢

时间:2020-12-01 08:20:15

今天发现的需求,在官方文档找到说法:

In English, that means start with any non-'defaults' keyword argument that doesn’t contain a double underscore (which would indicate a non-exact lookup). Then add the contents of defaults, overriding any keys if necessary, and use the result as the keyword arguments to the model class. As hinted at above, this is a simplification of the algorithm that is used, but it contains all the pertinent details. The internal implementation has some more error-checking than this and handles some extra edge-conditions; if you’re interested, read the code.

If you have a field named defaults and want to use it as an exact lookup in get_or_create(), just use'defaults__exact', like so:

Foo.objects.get_or_create(defaults__exact='bar', defaults={'defaults': 'baz'})

所以,用__exact指定即可,比如,我所面对的:
obj, created = Table.objects.update_or_create(
        dv__exact=dv_f, description=description)