I have a model serializer for a date field and a time field. The model and serializer look like this:
class OrderDate(TimeStampedModel):
order = models.ForeignKey(Order, related_name='dates', on_delete=models.CASCADE, null=True, blank=True)
date = models.DateField()
from_hour = models.TimeField()
to_hour = models.TimeField()
class OrderDateSerializer(serializers.ModelSerializer):
class Meta:
model = OrderDate
fields = ['id', 'date', 'from_hour', 'to_hour']
Now I use this serializer as a nested serializer in my order model and I added a validator like this:
class BaseOrderSerializer(serializers.ModelSerializer):
dates = OrderDateSerializer(many=True)
@staticmethod
def validate_dates(value):
return OrderService.validate_dates(value)
The value object inside the validated_dates method is an ordereddict which has datetime objects as value. Example value like this:
[OrderedDict([('date', datetime.date(2020, 12, 16)), ('from_hour', datetime.time(11, 0)), ('to_hour', datetime.time(15, 0))])]
Now I want to use the OrderService.validate_dates method a second time outside the serializer like this:
date_serializer = OrderDateSerializer(data=request.data, many=True)
date_serializer.is_valid(raise_exception=True)
OrderService.validate_dates(date_serializer.data)
The problem here is, that the serialized data now is an ordered dict with string values instead of datetime objects.
[OrderedDict([('id', None), ('date', '2020-12-16'), ('from_hour', '11:00:00'), ('to_hour', '15:00:00')])]
That results in an type error inside my method. Is there any way to change this and have the same value types in the ordered dicts?
question from:
https://stackoverflow.com/questions/65907959/drf-serializer-behaves-differently-when-using-as-nested-serializer