Skip to content Skip to sidebar Skip to footer

How To Do ...on Duplicate Key Update... In Django

Is there a way to do the following in django's ORM? INSERT INTO mytable VALUES (1,2,3) ON DUPLICATE KEY UPDATE field=4 I'm familiar with get_or_create, which takes default values,

Solution 1:

I'm familiar with get_or_create, which takes default values, but that doesn't update the record if there are differences in the defaults.

update_or_create should provide the behavior you're looking for.

Item.objects.update_or_create(
    id=1,
    defaults=fields,
)

It returns the same (object, created) tuple as get_or_create.

Note that this will still perform two queries, but only in the event the record does not already exist (as is the case with get_or_create). If that is for some reason unacceptable, you will likely be stuck writing raw SQL to handle this, which would be unfortunate in terms of readability and maintainability.

Solution 2:

I think get_or_create() is still the answer, but only specify the pk field(s).

item, _ = Item.objects.get_or_create(id=1)
item.update(**fields)
item.save()

Post a Comment for "How To Do ...on Duplicate Key Update... In Django"