如何为DRF3序列化程序创建一个额外的非模型CharField



这是我的序列化程序:

class PostSerializer(serializers.ModelSerializer):
    postType = serializers.CharField(default='posts');
    class Meta:
        model = Post
        fields = ('id', 'usersVoted', 'post', 'postType')
        read_only_fields = ('id', 'owner', 'postType')

postType是我想要发送到前端的附加字段,字符串值为"posts"。我通过将它放在read_only_fields变量中来确保它是ReadOnly。问题是,我收到一条错误消息,上面写着:

AttributeError at /posts/
Got AttributeError when attempting to get a value for field `postType` on serializer `PostSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `Post` instance.
Original exception text was: 'Post' object has no attribute 'postType'.

我有办法解决这个问题吗?我认为不需要SerializerMethodField,因为我只是想将字符串"posts"添加到序列化程序中,这样就不需要整个函数了。

我相信您已经在DRF文档中找到了答案:http://www.django-rest-framework.org/api-guide/fields/#serializermethodfield

SerializerMethodField这是一个只读字段。。。它可以用于将任何类型的数据添加到对象的序列化表示中。

from django.contrib.auth.models import User
from django.utils.timezone import now
from rest_framework import serializers
class UserSerializer(serializers.ModelSerializer):
    days_since_joined = serializers.SerializerMethodField()
    class Meta:
        model = User
    def get_days_since_joined(self, obj):
        return (now() - obj.date_joined).days

更新:现在针对您的案例:

class PostSerializer(serializers.ModelSerializer):
    postType = serializers.SerializerMethodField()
    class Meta:
        model = Post
        fields = ('id', 'usersVoted', 'post')
        read_only_fields = ('id', 'owner')
    def get_postType():
        return "posts"

您得到了这个异常,因为read_only_fields应该来自模型,而postType不是模型字段。

相关内容

最新更新