2017-02-19 38 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