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?
--
Ticket URL: <https://code.djangoproject.com/ticket/33834>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
* status: new => closed
* type: Cleanup/optimization => New feature
* resolution: => duplicate
Comment:
Duplicate of #3182.
--
Ticket URL: <https://code.djangoproject.com/ticket/33834#comment:1>
Comment (by Anton Danilchenko):
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.
--
Ticket URL: <https://code.djangoproject.com/ticket/33834#comment:2>
Comment (by Mariusz Felisiak):
It's exactly the same. It's titled ''"model **instance update()** method
and ..."'' and was rejected by
[https://code.djangoproject.com/ticket/3182#comment:13 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)
> }}}
--
Ticket URL: <https://code.djangoproject.com/ticket/33834#comment:3>