user1094786
user1094786

Reputation: 6800

Create if doesn't exist

I have a Django application that reads data from a web API and puts it in a database.
Is there a way to create a new object from a mode but prevent the duplicate exception if the object already exists?

In other words, is there a way to save an object, but to just do nothing if it already exists?

Upvotes: 110

Views: 84726

Answers (4)

Abhishek Pratap Singh
Abhishek Pratap Singh

Reputation: 761

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()

Upvotes: 7

crperez
crperez

Reputation: 127

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

Upvotes: 2

Benoit Blanchon
Benoit Blanchon

Reputation: 14521

In Django 1.7, you can also do:

Model.objects.update_or_create()

Upvotes: 52

second
second

Reputation: 28637

Model.objects.get_or_create()

Upvotes: 207

Related Questions