Prefetch invalidation on an update operation

18 views
Skip to first unread message

Clément Hallet

unread,
Apr 17, 2020, 4:39:09 AM4/17/20
to Django REST framework
Hello,

In a ModelViewset, a prefetch_related is set with an extra "order_by" :

def filter_queryset(self, qs):
    qs
= super().filter_queryset(qs)
    qs
= qs.prefetch_related(
       
Prefetch(
           
"related_data",
            queryset
=Record.objects.order_by(
               
"ts_update"
           
),
       
),
   
)
   
return qs

It is well applied on DRF retrieve operation. But on an update, after the changes have been applied, this prefetch_related is discarded. I completly understand why the cached data must be refreshed after the perform_update. But in the case here, it also removes the semantic meaning of the query, leading to the resulting data differs between a PUT and a later GET calls.

I cannot act in the perform_update method since the invalidation comes after and the only workaround I can think of is :

def update(self, request, *args, **kwargs):
       
super().update(request, args, kwargs)
       
return self.retrieve(request)

But that doesn't feel right, replacing the response of a base method by the one from an other. Could it be done differently ?

Cheers,

--
Clément Hallet

Linovia

unread,
Apr 17, 2020, 5:52:00 AM4/17/20
to Django REST framework
Indeed the preftech cache is emptied before returning the result of an update:

This is due to some side effects with many to many fields after an update:

I’m afraid you’ll have to override the update method.

Regards,
Xavier O.
--
You received this message because you are subscribed to the Google Groups "Django REST framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-rest-fram...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-rest-framework/a151e1f4-51ac-451c-8d9a-9c077a603208%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages