Django Rest Framework-在同一个视图集中返回不同的序列化器

时间:2018-09-16 08:59:23

标签: python django django-rest-framework

我有两个模型:

class Hunter(Model):
    name = CharField()

搜索

class Target(Model):
    name = CharField()
    user = ForeignKey(User) 
    approved_hunters = ManyToManyField(Hunter)

我的序列化器是

class AnonymousTargetSerializer(ModelSerializer):
    class Meta:
        name = 'target'
        model = Target
        fields = ['id',]

还有

class TargetSerializer(ModelSerializer):
    class Meta:
        name = 'target'
        model = Target
        fields = ['id',]

我想成为我的观点集

hunter = Hunter.objects.get(user=self.request.user)
if hunter in Target.approved_hunters.all()
    return TagetSerializer
else:
    return AnonymousTargetSerializer

但是,我似乎只能为视图集完成此操作,但不能在单个对象级别上进行过滤。

1 个答案:

答案 0 :(得分:1)

如果您需要基于某些属性来修改对象的表示形式,则可以覆盖序列化器的to_representation方法:

class TargetSerializer(ModelSerializer):
    class Meta:
        name = 'target'
        model = Target
        fields = ['id',]

    def to_representation(self, obj):
        hunter = Hunter.objects.get(user=self.context['request'].user)
        if hunter not in Target.approved_hunters.all():
            return AnonymousTargetSerializer(obj).data
        return super().to_representation(obj)

在视图集中,您无需进行任何自定义,只需使用TargetSerializer

serializer_class = TargetSerializer