Proposal: `create_or_update` method on query sets, managers, and related managers.

12 views
Skip to first unread message

Tai Lee

unread,
Sep 11, 2008, 1:04:20 AM9/11/08
to Django developers
On a few occasions I've found myself doing something like:

instance, created =
Model.objects.get_or_create(something=something, ..., defaults={
'somethingelse': somethingelse,
...
})
if not created:
instance. somethingelse = somethingelse
...
instance.save()

I'd like to propose a `create_or_update` method, similar to
`get_or_create`, which would work like this:

instance, created =
Model.objects.create_or_update(something=something, defaults={
'somethingelse': somethingelse,
})

If `instance` doesn't exist, it will be created with the specified
kwargs and `defaults`. If it does exist, it will be updated with
`defaults`. What does everyone think?

Bas van Oostveen

unread,
Sep 12, 2008, 3:53:40 AM9/12/08
to django-d...@googlegroups.com
Most of the times i have some extra condition in there.

if not created and modified>instance.modified:
for key, value in defaults_dict.items():
setattr(instance, key, value)
instance.save()

Now this extra clause can be fairly arbitrary.

A generic piece of code could check if there's any difference
between the defaults dict and the instance, then update those
differences and save the instance. Drawback is that wouldn't be very
fast but at least better then continuously saving the model imho.

def create_or_update(...):
updated = False
obj, created = Model.objects.get_or_create(something=something, ...,
defaults_dict = defaults_dict)
if not created and any(value!=getattr(obj, key) for key, value in
defaults_dict.items()):
# TODO: only update differences here (nicer then updating all?)
for key, value in defaults_dict.items():
setattr(obj, key, value)
obj.save()
updated = True
return obj, created, updated

Guess something like this could/would also be a nice snipplet to put on
django snipplets :)

Nathaniel Whiteinge

unread,
Sep 12, 2008, 11:49:36 AM9/12/08
to Django developers
On Sep 10, 11:04 pm, Tai Lee <real.hu...@mrmachine.net> wrote:
> I'd like to propose a `create_or_update` method, similar to
> `get_or_create`

FYI: there is an old ticket (with patch) for this called
update_or_create [1].

.. [1] http://code.djangoproject.com/ticket/3182
Reply all
Reply to author
Forward
0 new messages