Przemek Przemek - 1 year ago 39
Python Question

how to use get_object_or_404 with order_by('?') to get random image

I want to get random object from model but if there are no data in database I want to return 404 page.

This like of code works for me well:


but I want to use this python shortcut to get obect or 404

so I tried this:

dummy_image = get_object_or_404(DummyImage).order('?').first().image_url.url

but It dosent't work and causes issues. It says that it returned more than two object(?)

How do I solve the problem?

Answer Source

The get_object_or_404 shortcut uses get(), so it will raise an error if the filtered queryset returns more than one object.

You could slice the queryset to limit it to one object:

dummy_image = get_object_or_404(DummyImage.objects.order_by('?')[:1]).image_url.url

Alternatively, you could raise the Http404 exception manually. This code is a bit longer but you might find it clearer what is going on.

from django.http import Http404

dummy_image = DummyImage.objects.order_by('?').first()
if dummy_image is None:
    raise Http404
    dummy_image = dummy_image.image_url.url