Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
263 views
in Technique[技术] by (71.8m points)

python - DRF Serializer behaves differently when using as nested serializer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...