#34144: Casting a string inside a JSONField into an integer does not work on
PostgreSQL
-------------------------------------+-------------------------------------
Reporter: clement- | Owner: nobody
escolano |
Type: Bug | Status: new
Component: Database | Version: 4.1
layer (models, ORM) | Keywords: postgresql,
Severity: Normal | jsonfield, cast
Triage Stage: | Has patch: 0
Unreviewed |
Needs documentation: 0 | Needs tests: 0
Patch needs improvement: 0 | Easy pickings: 0
UI/UX: 0 |
-------------------------------------+-------------------------------------
Hello
When casting an integer represented as a string inside a JSONField on
PostgreSQL, there is the following error:
{{{
django.db.utils.DataError: cannot cast jsonb string to type integer
}}}
To reproduce the error, you can create a simple model with a JSONField:
{{{
class MyModel(models.Model):
data = models.JSONField()
MyModel.objects.create(data={"value": "3"})
MyModel.objects.annotate(actual_value=Cast("data__value",
output_field=IntegerField())).first()
}}}
The produced query is the following:
{{{
SELECT "myapp_mymodel"."id",
(("myapp_mymodel"."data" -> 'value'))::integer AS "actual_value"
FROM "myapp_mymodel"
LIMIT 1;
}}}
This [https://stackoverflow.com/a/25810945 stackoverflow question] hints
that adding an extra ">" after "->" fixes it and indeed the following
query returns the correct result:
{{{
SELECT "myapp_mymodel"."id",
(("myapp_mymodel"."data" ->> 'value'))::integer AS "actual_value"
FROM "myapp_mymodel"
LIMIT 1;
}}}
The code is already working on SQLite.
--
Ticket URL: <https://code.djangoproject.com/ticket/34144>
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/0107018456c80b1c-1bb0c3e9-687d-4374-b99d-c7a4a477a92d-000000%40eu-central-1.amazonses.com.