Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

What is the use of Django object.get_or_create ()

Shulou Source: shulou.com Published: 2022-06-01 16:14:31 10月02日 Update

What is the use of Django object.get_or_create ()? I believe many inexperienced people don't know what to do about it. Therefore, this paper summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.

Use get_or_create ()

Mode of use

User, b = User.objects.get_or_create (u_id=1, name= "Zhang San", defaults= {'address':' Shanghai'}) print (user)

Equivalent to

Users = User.objects.get (u_id=1, name= "Zhang San") if user: print (user) else: user = User.objects.create (u_id=1, name= "Zhang San", address= "Shanghai") print (user) instructions about get_or_create ()

Get_or_create, as the name implies, when querying or creating a piece of data, the first thing to do is to query whether there is such a value. If so, return it. If not, create it.

Get_or_create returns a tuple, with the first value being the data found or created, and the second value being a Boolean indicating whether the creation operation was performed.

Similar to using get queries, MultipleObjectsReturned is triggered when more than one piece of data is found.

Creating it is similar to creating it with create.

If you are using MySQL, be sure to use the READ COMMITTED isolation level instead of the default REPEATABLE READ, otherwise you will encounter a situation where get_or_create throws IntegrityError but the object does not exist in the next get () call.

After reading the above, have you mastered the method of using Django object.get_or_create ()? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

Tags: Method time query data Zhang San usage content more problem Shanghai helpless as the name suggests for this next reason for this object Boolean situation skill Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Xiaomi NVidia macOS Huawei Redmi