我有两个模型:
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
但是,我似乎只能为视图集完成此操作,但不能在单个对象级别上进行过滤。
答案 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