Reputation: 337
I want to return an object from my get_object_or_404
method but my query returns multiple objects. Is there a way to get last or first item?
This is how I do it:
return get_object_or_404(BatchLog, batch_id=self.kwargs["pk"])
I know it is not possible but this is kind of what I need:
return get_object_or_404(BatchLog, batch_id=self.kwargs["pk"].last())
Upvotes: 2
Views: 2557
Reputation: 2861
As the documentation says, you can use a QuerySet
instance instead of the model's class.
This should work:
return get_object_or_404(
BatchLog.objects.order_by('-date')[:1],
batch_id=self.kwargs["pk"],
)
Notice that we need to limit the QuerySet
instead of using .first()
or .last()
that would give us the object.
But it may actually be better to do it manually:
try:
return BatchLog.objects.filter(batch_id=self.kwargs["pk"])[0]
except IndexError:
raise Http404('No logs for this id')
Upvotes: 3
Reputation: 801
get_object_or_404
is equivalent to :
from django.http import Http404
def my_view(request):
try:
obj = MyModel.objects.get(pk=1)
except MyModel.DoesNotExist:
raise Http404("No MyModel matches the given query.")
In your case you could do :
try:
obj = MyModel.objects.filter(pk=1).last()
except:
raise Http404("No MyModel matches the given query.")
or better, if you have a way to order them:
try:
obj = MyModel.objects.order_by('date_created').filter(pk=1).last()
except:
raise Http404("No MyModel matches the given query.")
Upvotes: 1