how to use get_object_or_404 with order_by('?') to get random image
<p>I want to get random object from model but if there are no data in database I want to return 404 page.</p>

<p>This line of code works for me well:</p>

<pre><code>    dummy_image=DummyImage.objects.order_by('?').first().image_url.url
</code></pre>

<p>but I want to use the <code>get_object_or_404</code> shortcut.</p>

<p>So I tried this:</p>

<pre><code>dummy_image = get_object_or_404(DummyImage).order('?').first().image_url.url
</code></pre>

<p>but it dosent't work and causes issues. It says that it returned more than two objects.</p>

<p>How do I solve the problem?</p>

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

<p>You could slice the queryset to limit it to one object:</p>

<pre><code>dummy_image = get_object_or_404(DummyImage.objects.order_by('?')[:1]).image_url.url
</code></pre>

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

<pre><code>from django.http import Http404

dummy_image = DummyImage.objects.order_by('?').first()
if dummy_image is None:
    raise Http404
else:
    dummy_image = dummy_image.image_url.url
</code></pre>

python django