Opened 3 years ago
Closed 3 years ago
#34500 closed Bug (duplicate)
use annotate return feild, Error capture does not work
| Reported by: | ajin | Owned by: | ajin |
|---|---|---|---|
| Component: | Database layer (models, ORM) | Version: | 4.2 |
| Severity: | Normal | Keywords: | json decode |
| Cc: | Triage Stage: | Unreviewed | |
| Has patch: | no | Needs documentation: | no |
| Needs tests: | no | Patch needs improvement: | no |
| Easy pickings: | yes | UI/UX: | no |
Description
when I use this sql
return data
testcase
data = table.objects.annotate( array_length=Func(F('feild'), function='jsonb_array_length') ).filter(array_length__gt=1).only("feild")[:5] print(data.query) for i in data: print(model_to_dict(i))
sqldata
data = [[1, '[{"key": "value"}]', 1]]
but when feild use from_db_value function, Error capture has no effect,because json load int data, and can not return value
try: return json.loads(value, cls=self.decoder) except json.JSONDecodeError: return value
Change History (6)
comment:1 by , 3 years ago
| Owner: | changed from to |
|---|---|
| Status: | new → assigned |
comment:2 by , 3 years ago
| Has patch: | unset |
|---|---|
| Resolution: | → worksforme |
| Status: | assigned → closed |
comment:3 by , 3 years ago
model_to_dict is not import,That's a recurring example , this code can not return value, if value is int, that can not return true data
try: return json.loads(value, cls=self.decoder) except json.JSONDecodeError: return value
comment:4 by , 3 years ago
that can not print return
import json try: json.loads(3) except json.JSONDecodeError: print("return")
comment:5 by , 3 years ago
| Resolution: | worksforme |
|---|---|
| Status: | closed → new |
comment:6 by , 3 years ago
| Resolution: | → duplicate |
|---|---|
| Status: | new → closed |
JSONField.from_db_value() is a part of Django internals and it works as expected. value returned from a database should be a string. If you want to use Func() which returns a type other than the field you passed in, you should use the output_field argument, e.g.
Func(F('field'), function='jsonb_array_length', output_field=IntegerField())
Duplicate of #31973.
Thanks for the report, however I really don't understand what kind of issue you're trying to report. Using
model_to_dict()on models withJSONField()works for me. Please try to be more descriptive and provide a sample project or a reproducible scenario.