创建 if 不存在

我有一个 Django 应用程序,它从 web API 中读取数据并将其放入数据库中。
是否有一种方法可以从模式创建一个新对象,但是如果对象已经存在,就可以防止重复异常?

换句话说,有没有一种方法可以保存一个对象,但是在它已经存在的情况下什么也不做?

69061 次浏览

In Django 1.7, you can also do:

Model.objects.update_or_create()

Looks like in newer versions of Django the save() function does an UPDATE or INSERT by default. See here.

It can be achieved using Model.objects.get_or_create()

Example

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

Any keyword arguments(here first_name and last_name) passed to get_or_create() — except an optional one called defaults — will be used to query in database(find the object) in database.

It returns a tuple, if an object is found, get_or_create() returns a tuple of that object and False.

Note: Same thing can also be achieved using try except statements
Example:

try:
obj = Person.objects.get(first_name='John', last_name='Lennon')
except Person.DoesNotExist:
obj = Person(first_name='John', last_name='Lennon', birthday=date(1940, 10, 9))
obj.save()