#32406: Allow QuerySet.update() to return fields on supported backends.
-------------------------------------+-------------------------------------
Reporter: Tom Carrick | Owner: aivarsk
Type: New feature | Status: assigned
Component: Database layer | Version: dev
(models, ORM) |
Severity: Normal | Resolution:
Keywords: | Triage Stage: Accepted
Has patch: 0 | Needs documentation: 0
Needs tests: 0 | Patch needs improvement: 0
Easy pickings: 0 | UI/UX: 0
-------------------------------------+-------------------------------------
Changes (by aivarsk):
* owner: (none) => aivarsk
* status: new => assigned
Comment:
I have a proof of concept in my branch, I will clean up and open a PR this
week. But I took a slightly different approach so I would like to get some
feedback.
I added a new `.update_returning` method that returns a query set instead
of changing the existing `.update` that returns a number. That allows us
to do things like:
we can get the model after the update which is the main use case IMO. I
have used this approach in accounting systems, there are some articles
showing when it's useful https://hakibenita.com/django-concurrency#update-
and-immediately-return
{{{
#!python
updated = (
UpdateReturningModel.objects.filter(key=obj.key)
.update_returning(hits=F("hits") + 1)
.get()
)
}}}
we can also do some lazy loading
{{{
#!python
updated = (
UpdateReturningModel.objects.filter(key=obj.key)
.update_returning(hits=F("hits") + 1)
.only("hits")
.get()
)
updated = (
UpdateReturningModel.objects.filter(key=obj.key)
.update_returning(hits=F("hits") + 1)
.defer("hits", "content")
.get()
)
}}}
or keep working without models
{{{
#!python
updated = UpdateReturningModel.objects.update_returning(
hits=F("hits") + 1
).values("pk", "hits")
updated = UpdateReturningModel.objects.update_returning(
hits=F("hits") + 1
).values_list("hits", flat=True)
}}}
--
Ticket URL: <https://code.djangoproject.com/ticket/32406#comment:11>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
--
You received this message because you are subscribed to the Google Groups
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/django-updates/0107018acb5f924c-ad7a63e0-6c88-4e1b-9e57-256e79a38e84-000000%40eu-central-1.amazonses.com.