Searched throughout SO to find the matching questions doesn't answer mine as there are only few explanations. So hoping to get an answer here.
I have a model named "testcase" with pk set as "testcase_name". On update operation in the serializer, instead of updating a new instance is created everytime. I suspect it is because of the pk.
serializer.py
class TestcaseSerializer(serializers.ModelSerializer):
class Meta:
model = testcase
lookup_field = 'testcase_name'
fields = ("testcase_name", 'description')
def update(self, instance, validated_data):
print(instance) # returns test2 instead it should be test1 which is the current instance
# ret = super(TestcaseSerializer, self).update(instance, validated_data)
[setattr(instance, key, value)
for key, value in validated_data.items()]
instance.save()
print(instance)# returns test2
return instance
models.py
class testcase(models.Model):
testcase_name = models.CharField(
max_length=20, primary_key=True)
description = models.CharField(max_length=100, blank=True)
def __str__(self):
return self.testcase_name
views.py
class Testcaseviewset(viewsets.ModelViewSet):
queryset = testcase.objects.all()
serializer_class = TestcaseSerializer
lookup_field = 'testcase_name'
Is there any way to solve this in the serializer itself not from the views.
question from:
https://stackoverflow.com/questions/65875702/drf-doesnt-update-instead-create-new-instance-in-modelserializer 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…