Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
253 views
in Technique[技术] by (71.8m points)

python - DRF doesn't update instead create new instance in modelserializer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...