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!