0

I know in django we can create an object model easily by using something like this

AbcModel.objects.create(field1='a', field2='b')

But this would create the object even if it already exists. I know I can use filter() then use the exist() to check if the object already exist then decide to update or create.

But is there an easier and faster way to do this? Since, there is get_or_create so I am curious if there's something similar.

Thanks in advance

EDIT: I thought of something like this

new = AbcModel.objects.create(field1='a')
new[0].field2 = 'c'
new[0].save()

There might be more fields and field1 will not always be a would be others like b, c and maybe a again.

Just being curious if there is an easier faster way and not saying get_or_create wouldn't get what I want / need

Tsuna
  • 2,098
  • 6
  • 24
  • 46
  • 1
    What does `get_or_create()` not do that you want it to do? – dhke May 15 '17 at 18:21
  • Possible duplicate of [Correct way to use get\_or\_create?](http://stackoverflow.com/questions/1941212/correct-way-to-use-get-or-create) – Hamms May 15 '17 at 18:48

2 Answers2

1

As you said about get_or_create, you could do:

abc_instance, created = AbcModel.objects.get_or_create(field1='a', field2='b')

That would bring you the existent/created object as the first argument and a boolean as the second argument, that defines if it was got or created.

Additionally, field1 and field2 will be used for the filter, but you can set the defaults attribute, which will update the existing entry or be used for its creation.

abc_instance, created = AbcModel.objects.get_or_create(
    field1='a', field2='b',
    defaults={'field3': 'c', 'field4': 'd'}
)
0

You can use update_or_create: https://docs.djangoproject.com/en/2.0/ref/models/querysets/#update-or-create

However if the field you filter by is not unique, you might end up getting a MultipleObjectsReturned exception.

Another way to do this could be:

num_updated = AbcModel.objects.filter(field1='a').update(field2='c')
if num_updated == 0:
    model = AbcModel.objects.create(field1='a', field2='c')

In num_updated you will have the number of rows updated in the first line of code.

I hope this helps a bit!

jbondia
  • 253
  • 2
  • 7