2017-02-19 40 views
1

在我的模型中,我有UserProfile,它有一個名爲public_profile的字段。對於Event模型(另一種模式)的串行是:Django Rest動態選擇字段進行渲染

class EventSerializer(serializers.ModelSerializer): 

    going = UserProfSerializer(read_only=True, many=True) 
    notGoing = UserProfSerializer(read_only=True, many=True) 

    class Meta: 
    model = Event 
    fields = ('name', 'place', 'date', 'going', 'notGoing', 'slug') 

goingnotGoing是在數據庫中用戶配置一個不少一對多的關係。我的問題是如何選擇哪些字段在UserProfSerializer中呈現,具體取決於配置文件配置,如果它是公開的或不公開的。例如,我想讓用戶PK和個人資料圖片顯示,但不是用戶名。

回答

2

你可以覆蓋to_representation方法:

class UserProfSerializer(serializers.ModelSerializer): 

    PUBLIC_FIELDS = ('id', 'avatar') 

    class Meta: 
     model = UserProfile 
     fields = ('id', 'username', 'avatar') 

    def to_representation(self, obj): 
     response = super(UserProfSerializer, self).to_representation(obj) 
     if not obj.public_profile: 
      for field in response: 
       if field not in self.PUBLIC_FIELDS: 
        del response[field] 
     return response 
+0

謝謝你,成功了! –

+0

如果你喜歡它,不要忘記對答案進行投票:] – JoseKilo