U
U
un1t2015-10-15 18:20:05
Django
un1t, 2015-10-15 18:20:05

Why does Djnago Rest Framework return old related object information on update?

The problem manifests itself with related objects

class Tag(models.Model):
    pass

class Photo(models.Model):
    tags = models.ManyToManyField(Tag, related_name='tags', blank=True)

class PhotoWriteSerializer(serializers.ModelSerializer):
    class Meta:
        model = Photo

class PhotoViewSet(viewsets.ModelViewSet):
    queryset = Photo.objects.all()
    serializer_class = PhotoReadSerializer

    def get_serializer_class(self):
        if self.request.method in permissions.SAFE_METHODS:
            return PhotoReadSerializer
        return PhotoWriteSerializer

I create a photo.
I send a request to update the tags
PATCH /photos/ {'id': 55, 'tags': [1,2,3]}
Tags are saved normally, but the old value comes in the response, i.e. empty in this case.
If I send GET then I see that the tags have been updated, 'tags' comes: [1,2,3].

Answer the question

In order to leave comments, you need to log in

1 answer(s)
U
un1t, 2015-10-16
@un1t

In general, I dug and dug this bug, made a separate project - it is not reproduced.
In general, such an interesting point turned out to be
. Such a code as above works, but such a code does not work

class PhotoViewSet(viewsets.ModelViewSet):
    queryset = Photo.objects.all().prefetch_related('tags')
    serializer_class = PhotoReadSerializer

While as a temporary solution, I see you can use this option
class PhotoViewSet(viewsets.ModelViewSet):
    queryset = Photo.objects.all().prefetch_related('tags')
    serializer_class = PhotoWriteSerializer

    def get_queryset(self):
        if self.request.method in permissions.SAFE_METHODS:
            return self.queryset
        return Photo.objects.all()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question