[Fixed]-Django Rest Framework – Updating a model using 'depth'

1πŸ‘

it is very late to answer this now, but I found a simple solution which is make the depth dynamic, 0 when create or update and 1 when get

just add this init method to your serializer

def __init__(self, *args, **kwargs):
    super(ProcessSerializer, self).__init__(*args, **kwargs)
    request = self.context.get('request')
    if request and (request.method == 'POST' or request.method == 'PUT'):
        self.Meta.depth = 0
    else:
        self.Meta.depth = 1

thanks to the 2nd answer of this question
depth = 1 doesn't work properly and it's saves Null in ManyToManyField and ForeignKey fields in Django Rest Framework

0πŸ‘

Answer after discussion

class ItemSerializer(serializers.ModelSerializer):
    condition = ConditionSerializer()
    class Meta:
        model = Item
        depth = 1

    def update(self, instance, validated_data):
        condition_inst = Condition.objects.get(**validated_data.pop('condition'))
        instance.condition_id = condition_inst.id
        for item in validated_data:
            if Item._meta.get_field(item):
                setattr(instance, item, validated_data[item])

        instance.save()
        return instance
πŸ‘€Akram Parvez

0πŸ‘

method 1:
try this if you want to get data in depth = 1.

class ItemSerializer(serializers.ModelSerializer):
    condition = ConditionSerializer(read_only = True)
    class Meta:
        model = Item
        fields = '__all__'

if you want to get depth > 1 than mention depth in ConditionSerializer.

Method 2 :

from rest_framework.permissions import SAFE_METHODS

class ItemSerializer(serializers.ModelSerializer):
    class Meta:
        model = Item
        fields = '__all__'

def __init__(self, *args, **kwargs):
    super(ItemSerializer, self).__init__(*args, **kwargs)
    request = self.context.get('request')
    if request.method in SAFE_METHODS:
        self.Meta.depth = 1
    else:
        self.Meta.depth = 0

Method 3 :

write two serializers one with depth one without depth.

write your view like this.

class ItemView(ModelViewSet):
    queryset = Item.objects.all()

def get_serializer_class(self):
    if self.request.method in SAFE_METHODS:
        return serializerwithdepth
    else:
        return serializerwithoutdepth
πŸ‘€p kushwaha

Leave a comment