django - Rest Framework 序列化程序方法字段

标签 django python-3.x django-rest-framework

class BagSerializer(serializers.ModelSerializer):
    order_date = serializers.SerializerMethodField()

    class Meta:
        model = Bag
        fields = ('order_date')

    def get_order_date(self, obj):
        print('Order date called', obj)

这是 View :

class BagViewSet(viewsets.ModelViewSet):
queryset = Bag.objects.all()
serializer_class = BagSerializer

    def create(self, request):
        try:
            print('Inside create viewset')
            serializer = self.get_serializer(data=request.data)
            if serializer.is_valid():
                print('serializer passed', serializer.validated_data)
            else:
                print('Serializer failed', serializer.errors)
                return Response(serializer.errors)
        except Exception as e:
        print('exception raised--------', e)
    return Response('Boom')

序列化器方法字段未被调用,其数据也未显示在 validated_data 中,序列化器的 is_valid() 方法返回 True。 为什么不考虑序列化程序方法字段

最佳答案

SerializerMethodField是只读字段。来自docs :

Read-only fields are included in the API output, but should not be included in the input during create or update operations. Any 'read_only' fields that are incorrectly included in the serializer input will be ignored.

如果 order_date 与某些模型字段相关,您可以使用 DateFieldsource 参数:

order_date = serializers.DateField(source='model_field_name')

关于django - Rest Framework 序列化程序方法字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50236824/

相关文章:

python - 是否可以单独使用 Django 管理创建面向最终用户的站点?

python - 在 aiohttp 请求中发送用户凭据

python - 为什么 Python 解包运算符适用于无序集合

python - 仅当相邻列中同一行的单元格为空白时,如何基于字符拆分字符串

python - Django REST 框架——如何将外键解析为实际值,而不是索引?

mysql - 此更改如何影响此数据库查询的速度?

django - list_display - 方法的 bool 图标

python - Django Rest-Framework 序列化程序忽略模型 ID

Django:显示用户名而不是 ID,如何?

python - 在 django 中向租户管理员隐藏公共(public)模型