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

tom*_*mrs 20 python django

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

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

函数如何get_or_create返回两个值?

Sve*_*ach 29

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

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


AP2*_*257 6

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

请参阅 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)})
Run Code Online (Sandbox Code Playgroud)