开发者

How does the get_or_create function in Django return two values?

开发者 https://www.devze.com 2023-02-05 03:46 出处:网络
I have used the get_or_create function 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 ret

I have used the get_or_create function 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.

Normally, a function can re开发者_运维百科turn a single value or a collection of values like a tuple, list or a dictionary.

How does a function like get_or_create return two values?


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

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


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:

# 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)})


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

0

精彩评论

暂无评论...
验证码 换一张
取 消