Validate 2 dimension list input in drf serializer

305 Views Asked by At

I have a ArrayField in model:

from django.contrib.postgres.fields import ArrayField

field1 = ArrayField(
    ArrayField(
        models.TimeField(null=True, default=None),
        size=2
    ),
    size=7
)

I have CreateAPIView which needs to validate field1 in the serializer.

I send following data in post request from APITestCase class to test the API:

'field1': [
    ['10:00:00', '15:00:00']
],

In Api view I receive list of string instead of list of list:

'field1': ["['10:00:00', '15:00:00']"]

Using ListField in serializer gives error since the input data is list[str] instead of list[list].

field1 = serializers.ListField(
    child=serializers.ListField(
        child=serializers.TimeField(allow_null=True),
        allow_empty=False
    ),
    allow_empty=False
)
  1. Is there another way of sending list[list] as input data to post request?
  2. Is there a way to validate list[list] using serializers.ListField ?

I read this answer. It works when input is list[str]

1

There are 1 best solutions below

0
Aseem On

When making a post request adding format=json solves the problem:

self.client.post(url,data=data,format='json')

Now the data received in API is of format list[list]

The validation method mentioned in the question works fine.