#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 ajin, 14 months ago

Owner: changed from nobody to ajin
Status: newassigned

comment:2 by Mariusz Felisiak, 14 months ago

Has patch: unset
Resolution: worksforme
Status: assignedclosed

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 with JSONField() works for me. Please try to be more descriptive and provide a sample project or a reproducible scenario.

comment:3 by ajin, 14 months 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 ajin, 14 months ago

that can not print return

import json

try:
    json.loads(3)
except json.JSONDecodeError:
    print("return")

comment:5 by ajin, 14 months ago

Resolution: worksforme
Status: closednew

comment:6 by Mariusz Felisiak, 14 months ago

Resolution: duplicate
Status: newclosed

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.

Note: See TracTickets for help on using tickets.
Back to Top