DRF - How to get a single item from a QuerySet?

Viewed 1384

I want to get objects with the pk I send through request but I want only one item from the queryset.

I want BatchLog objects that their batch_id is same as the pk and my query returns multiple items within that query. I just want one of them and it doesn't matter which one it is.

def get_queryset(self):
    return BatchLog.objects.filter(batch_id=self.kwargs["pk"])

It returns QuerySet<[BatchLog, BatchLog]> but I need QuerySet<BatchLog>

How can I achieve it?

Thanks.

2 Answers

You can just get the first one.

def get_queryset(self):
    return BatchLog.objects.filter(batch_id=self.kwargs["pk"]).first()

def get_object(self):
    queryset = self.get_queryset()
    return get_object_or_404(queryset)

You can slice the queryset such that it limits the number of results to one, so:

def get_queryset(self):
    return BatchLog.objects.filter(batch_id=self.kwargs['pk'])[:1]

If the filter thus matches multiple records, it will return a QuerySet that will contain one of these records, this is not per se the first/last one edited/created, this can be different each time you make a query.

If there are no items that match the filter, then this will be an empty QuerySet.

If you make use of filter_backends, then the above will not work, therefore it is better not to do this at the get_querset, but slice the result of filter_queryset:

class MyListAPIView(ListAPIView):
    # …

    def filter_queryset(self, *args, **kwargs):
        return super().filter_queryset(*args, **kwargs)[:1]
Related