David542
David542

Reputation: 110267

Run a django update but call the save method

Is there a way to do the following:

asset, _ = Asset.objects.get_or_create(system=item['system'], system_table=item['system_table'], ...)
Asset.objects.filter(pk=asset.pk).update(**item)

And also call the .save() method? I think I've read somewhere that you can run an update on the actual instance and not go through the objects manager. How would that be done? Currently I'm doing the following, which is quite repetitive and inefficient:

a = Asset.objects.filter(pk=asset.pk).update(**item)
a.save()

Upvotes: 0

Views: 1399

Answers (2)

JPG
JPG

Reputation: 88519

Since you already have the asset object, you can just make use of it.

# assuming that you have a `Asset` object in `asset` variable, somehow

item = {"foo": "foo-value"}
for field, value in items.items():
    setattr(asset, field, name)
asset.save()

You can also specify the update_fields parameter of save() method as

asset.save(update_fields=list(item.keys()))

Upvotes: 1

Code-Apprentice
Code-Apprentice

Reputation: 83537

The best way to do this is to just call save() directly. You will need to call get() instead of filter(), though.

Asset.objects.get(pk=asset.pk).save(update_fields=item)

This isn't a problem since your existing filter() is guaranteed to return a queryset with at most one Asset anyway. You just have to be sure that the given pk actually exists or wrap the get() call in a try...except block.

But...since you already have the Asset instance in asset, there's no reason to waste time with a DB query. Just call save directly on the object you have:

asset.save(update_fields=item)

Upvotes: 0

Related Questions