Python Django 中的 get_or_create 函数如何返回两个值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4706697/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 17:05:20  来源:igfitidea点击:

How does the get_or_create function in Django return two values?

pythondjango

提问by tomrs

I have used the get_or_createfunction on my models in Django. This function returns two values. One is the object itself and the other a boolean flag that indicates whether an existing object was retrieved or a new one created.

get_or_create在 Django 的模型上使用了该函数。此函数返回两个值。一个是对象本身,另一个是布尔标志,指示是检索了现有对象还是创建了新对象。

Normally, a function can return a single value or a collection of values like a tuple, listor a dictionary.

通常情况下,一个函数可以返回一个或多个值的像一个集合tuplelist或字典。

How does a function like get_or_createreturn two values?

像这样的函数如何get_or_create返回两个值?

采纳答案by Sven Marnach

get_or_create()simply returns a tuple of the two values. You can then use sequence unpackingto bind the two tuple entries to two names, like in the documentationexample:

get_or_create()简单地返回两个值的元组。然后,您可以使用序列解包将两个元组条目绑定到两个名称,如文档示例中所示:

p, created = Person.objects.get_or_create(
    first_name='John', last_name='Lennon',
    defaults={'birthday': date(1940, 10, 9)})

回答by AP257

It returns a tuple. It sounds like you knew that functions could do this, just not that you could assign the results directly to two variables!

它返回一个元组。听起来您知道函数可以做到这一点,只是不知道您可以将结果直接分配给两个变量!

See the Django documentation for get_or_create:

请参阅 Django 文档get_or_create

# Returns a tuple of (object, created), where object is the retrieved 
# or created object and created is a boolean specifying whether a new 
# object was created.

obj, created = Person.objects.get_or_create(first_name='John', last_name='Lennon',
                  defaults={'birthday': date(1940, 10, 9)})

回答by Bernhard Vallant

Using tuples/tuple unpacking is often considered as a quite "pythonic" wayof returning more than one value.

使用元组/元组解包通常被认为是返回多个值的一种非常“pythonic”的方式