2015-11-18 63 views
0

這是我的串行:如何爲DRF 3序列化程序創建附加的非模型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是我要發送到前端用「帖子」的字符串值附加字段。我通過將它置於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'添加到序列化程序中,因此不需要整個函數。

回答

1

我相信你在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" 
+0

嗯,我希望我不會需要一種方法。你提到它是隻讀字段。我能否使用'ReadOnlyField'完成同樣的事情?:http://www.django-rest-framework.org/api-guide/fields/#readonlyfield – user2719875

+0

不,ReadOnlyField再次與您的Model類相關。爲什麼使用SerializerMethodField時遇到問題?請參閱編輯的示例。 – Radek

0

因爲read_only_fields應該是從模型而postType不是模型場你說的異常。

+0

啊好的。那麼解決這個問題的方法是什麼?使用methodfield?別無退路? – user2719875

+0

如何直接將read_only參數推送到字段? postType = serializers.CharField(default ='posts',read_only = True) – Linovia

相關問題