Opened 5 years ago
Closed 5 years ago
#32021 closed New feature (duplicate)
Add support to update a JSONField with result from annotation
| Reported by: | Xavier Lesa | Owned by: | nobody |
|---|---|---|---|
| Component: | Database layer (models, ORM) | Version: | 3.1 |
| Severity: | Normal | Keywords: | JSONField, Models, Annotate |
| Cc: | Triage Stage: | Unreviewed | |
| Has patch: | no | Needs documentation: | no |
| Needs tests: | no | Patch needs improvement: | no |
| Easy pickings: | no | UI/UX: | no |
Description
I have a model with a JSONField and want to update in just one query like any other Field. Something like this:
# one query update
related_machinery = ActivityTracking.objects.filter(machinery=OuterRef('pk')).values('machinery')
sub_total = related_machinery.annotate(Sum('measure_value')).values('measure_value__sum')
avg_total = related_machinery.annotate(Avg('measure_value')).values('measure_value__avg')
Machinery.objects.filter(id=machinery_id).update(
measure_value=F('initial_measure_value') + sub_total,
metrics=avg_total
)
In example measure_value is a DecimalField and metrics is a JSONField. Also will be great if keys in JSONField was accessibles in update, like this:
Machinery.objects.filter(id=instance.machinery_id).update(
measure_value=F('initial_measure_value') + sub_total,
metrics__average_measure_value=avg_total
)
Note:
See TracTickets
for help on using tickets.
Duplicate of #29112.