#33834 closed New feature (duplicate)
Compact way to in-place update of the ORM model instance
| Reported by: | Anton Danilchenko | Owned by: | nobody |
|---|---|---|---|
| Component: | Database layer (models, ORM) | Version: | dev |
| Severity: | Normal | Keywords: | orm |
| Cc: | Triage Stage: | Unreviewed | |
| Has patch: | no | Needs documentation: | no |
| Needs tests: | no | Patch needs improvement: | no |
| Easy pickings: | no | UI/UX: | no |
Description
Hello,
I think that it will be useful to have such a methods to update the instance in-place, that saves a bit of typing:
book = Book.objects.get(pk=123) # Currently we do next book.title = "New title" book.year = 2022 book.save() # NEW WAY: Set multiple fields in-place book.set(title="New title", year=2022) book.save() # NEW WAY: Update multiple fields in-place book.update(title="New title", year=2022)
This way we can save on typing, and set fields (especially if we have them in a dict) easily. Or we can update an object with new field values and save it explicitly.
It can be implemented easily in the base Model class by adding two methods:
class Model:
def set(self, **kwargs):
for name, value ink wargs.items():
setattr(name, value)
def update(self, **kwargs):
self.set(kwargs)
return self.save()
My question is next - why it's no such obvious operations in the Django ORM yet? Is it done by purpose?
Change History (3)
comment:1 by , 3 years ago
| Resolution: | → duplicate |
|---|---|
| Status: | new → closed |
| Type: | Cleanup/optimization → New feature |
comment:2 by , 3 years ago
Hi @Mariusz Felisiak.
I see that you marked it as a duplicate of the very old ticket. But in that ticket it was discussed a different approach - to use the queriet.update() method to update one or few objects at the same time, and it was rejected in the end.
But I'm asking about a totally different approach - to use the instance.update() as a shorter form of what I described above. It's a different approach, but method name is the same in both tickets, but meaning is totally different.
Please re-evaluate this ticket one more time.
comment:3 by , 3 years ago
It's exactly the same. It's titled "model instance update() method and ..." and was rejected by Jacob:
It's pretty clear to me that
update()is a nonstarter; it's a single line of code::
def update(self, **kw): self.objects.filter(pk=self.pk).update(**kw)
Duplicate of #3182.