2

I have two models: where

class Hunter(Model):
    name = CharField()

searches for

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

my serializers are

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

and also

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

Im my viewsets I would like to:

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

However I only seem to get this done for the viewset, but cannot filter on an individual object level.

1 Answer 1

3

If you need to modify representation of object based on some attribute you can override serializer's to_representation method:

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)

In viewset you dont need any customization, just use TargetSerializer:

serializer_class = TargetSerializer
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.