Exclude a returned representation in django restframework

Viewed 29

I have a Serializer but I want to set a calculation whether to include it in serialized return objects or not.

class TradeSerializer(serializers.ModelSerializer):
    .
    .
    .
    .
    def to_representation(self, instance):
        ret = super().to_representation(instance)
        if ret['countdown'] < 5:
            # STOP! Do not return an object anymore!
            return
        return ret

But the syntax above will return something like ret[None]. I looking for an absolute exclusion

1 Answers

You can made custom queryset to filter out your countdown < 5 before serializing the objects. You cant filter out objects in serializer, this is not the purpose of serializers, but you can raise validation errors if you want.

Related