#33974 closed New feature (wontfix)
Serializer incorrectly serializes Integer ArrayField as string
| Reported by: | Arthur Hanson | Owned by: | nobody |
|---|---|---|---|
| Component: | Core (Serialization) | Version: | 4.0 |
| Severity: | Normal | Keywords: | |
| Cc: | Triage Stage: | Unreviewed | |
| Has patch: | no | Needs documentation: | no |
| Needs tests: | no | Patch needs improvement: | no |
| Easy pickings: | no | UI/UX: | no |
Description
If you define a model with an ArrayField of type Integer (PositiveSmallInteger, etc..) and use the built in serializer to json it will be serialized as an array of strings. Expected is that it will be serialized as an array of integers. For example, given the model below:
from django.db import models
# Create your models here.
from django.contrib.postgres.fields import ArrayField
from django.db import models
class Board(models.Model):
pieces = ArrayField(
base_field=models.PositiveSmallIntegerField()
)
If you create an object with "pieces = [1, 3, 5, ]" and either create a fixture or call serialize directly you will get an array of strings. The following management command shows the issue:
from django.core.management.base import BaseCommand, CommandError
from serializertest.models import Board
from django.core.serializers import serialize
import json
class Command(BaseCommand):
help = ''
def handle(self, *args, **options):
obj = Board.objects.first()
if not obj:
pieces = [1, 3, 5]
obj = Board()
obj.pieces = pieces
obj.save()
print(serialize('json', [obj]))
print(json.dumps(obj.pieces))
Output will be:
[{"model": "serializertest.board", "pk": 1, "fields": {"pieces": "[\"1\", \"3\", \"5\"]"}}]
[1, 3, 5]
Note: the serialize output an array of strings, while calling json directly will give the expected array of integers.
Attachments (2)
Change History (6)
by , 3 years ago
comment:1 by , 3 years ago
| Component: | Uncategorized → Core (Serialization) |
|---|---|
| Resolution: | → wontfix |
| Status: | new → closed |
| Type: | Uncategorized → New feature |
Thanks for the report however (de-)serialization works for me with ArrayField(base_field=models.PositiveSmallIntegerField()). Are there any practical issues with the current approach (except for your preferences)? Other complex fields (such as JSONField) are also serialized as strings. I'm afraid that the proposed change is backward incompatible and you can always use a custom serializer, if you need a different format.
follow-up: 3 comment:2 by , 3 years ago
FWIW, I would be favorable to fix this, if not too complex to do.
comment:3 by , 3 years ago
Replying to Claude Paroz:
FWIW, I would be favorable to fix this, if not too complex to do.
PoC is always welcome, I'm afraid that this will brake existing fixtures.
comment:4 by , 3 years ago
Arthur, would you like to work on a possible fix? (with no guarantee it will be accepted eventually)
example model file with arrayfield