[Django]-Get latest object with filter in django rest framework

9👍

✅

The porblem here ist the latest() method. This does not return a queryset but a single model instance. (like get(...))

so use:

def get_queryset(self):
    return self.queryset.filter(node_id=self.kwargs.get('node_pk')).order_by('-timestamp')

So if you want to have an endpoint for a single object you must not use DRF List* views/mixins.
The listviews assume you want to work with lists (=multiple objects). And so they rely on queryset resp. get_queryset. And a queryset should obviously be a queryset and not a model instance…

But there is also the RetrieveAPIView view included:

from rest_framework.generics import RetrieveAPIView

class LatestNodeConfigView(RetrieveAPIView):
    queryset = models.NodeConfig.objects.all()
    # add your serializer
    serializer_class = NodeConfigDetailSerializer

    def get_object(self, *args, **kwargs):
        return self.queryset.filter(node_id=kwargs.get('node_pk')).latest('timestamp')

0👍

You could also use python slicing for return single object into queryset:

self
  .queryset
  .filter(node_id=self.kwargs.get('node_pk'))
  .order_by('-timestamp')[:1]

Leave a comment