[Django]-How to exclude fields that are in one depth level with DRF?

5👍

The best way to do this is to use custom nested serializers. And expose the fields that you really want to expose to the frontend app. It is called the zero-trust approach. I personally prefer it over the exclude approach.

Let’s rewrite your serializer in a way to achieve the same result as depth =3

class Test_Serializer(serializers.ModelSerializer):
    testPieces = TimePiecesSerializer(many=True, read_only=True)
    resultTestsList = TimeResultSerializer(many=True, read_only=True)
    class Meta:
        model = Test_1
        fields = ["name", "category", "time", "testPieces", "resultTestsList"]

As you see I have added to nested serializer instead of depth=3

So here is the code for those custom serializers

class TimePiecesSerializer(serializers.ModelSerializer):
    class Meta:
        model = Test_pieces_1_question
        fields = ["question", "yesScore", "noScore"]


class TimeResultSerializer(serializers.ModelSerializer):

    class Meta:
        model = Result_tests_list_1
        fields = ["text", "score", "unicode"]

Using the above nesting serializer approach will give you the same results as depth and will also exclude the key id as it seems you are not interested in it.

You may need a little tunning according to your fields but it is a more promising approach over others.

Leave a comment