How to Remove or Skip Object Serialization in Django Rest Framework Based on Conditions?

class CreateAttributeSerializer(BaseAttributeSerializer):

    class Meta(BaseAttributeSerializer.Meta):
        fields=['id', 'required'] +  BaseAttributeSerializer.Meta.fields


    def to_representation(self, instance):
        attribute = super().to_representation(instance)
        current_display_order = int(instance.create_display_order)
        old_instance = self.context.get('old_instance', None)
        if old_instance:
            attributes = []
            old_attribute = self.context['old_attribute']
            if int(old_instance.create_display_order) == current_display_order:
                attributes = [old_attribute]
                attributes.append(attribute) 
            else:
                attributes.append(attribute)
            return attributes
        self.context['old_instance'] = instance 
        self.context['old_attribute'] = attribute

I need to conditionally skip an object during serialization in Django Rest Framework. If certain conditions are met, the object should not be included in the response at all, neither as None nor an empty list. How can I get rid of null,

[
    null,
    [
        {
            "id": 1,
            "required": false,
            "name": "price",
            "slug": "price"
        },
        {
            "id": 6,
            "required": true,
            "name": "currency",
            "slug": "currency",
            "choices": [
                "sum",
                "y.e"
            ]
        }
    ],
    [
        {
            "id": 2,
            "required": false,
            "name": "Chevrolet model",
            "slug": "chevrolet_model",
            "choices": [
                "Nexia",
                "Damas"
            ]
        }
    ],
]
Вернуться на верх