Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Since it's an attribute of the class, your queryset is getting <a href="https://docs.djangoproject.com/en/dev/topics/db/queries/#caching-and-querysets" rel="nofollow">evaluated and cached</a> when the class is loaded, i.e. when you start the dev server.</p> <p>I'd try pulling a list of primary keys, <a href="https://docs.djangoproject.com/en/dev/ref/models/querysets/#values-list" rel="nofollow">using <code>values_list()</code></a> — the <code>flat=True</code> example does exactly what you need. <a href="https://docs.djangoproject.com/en/dev/topics/cache/" rel="nofollow">Ideally cache that</a>. Pick a primary key at random and then use that to <code>get()</code> the actual object when you need it.</p> <p>So, how would that go? </p> <p>I'd define a method on the view. If you forget the caching, the implementation might go like this:</p> <pre><code># Lets use this... from random import choice def random_MyModel(self): """Method of RandomObject to pick random MyModel""" pks = MyModel.objects.values_list('pk', flat=True).order_by('id') random_pk = choice(pks) return MyModel.objects.get(pk=random_pk) </code></pre> <p>You might then want to cache the first look up here. The caching docs linked above explain how to do that. If you do cache the result look into the <a href="https://docs.djangoproject.com/en/1.0/ref/signals/#module-django.db.models.signals" rel="nofollow"><code>db.models</code> signals</a> to know when to invalidate — I guess you'd <code>post_save</code>, checking the <code>created</code> flag, and <code>post_delete</code>. </p> <p>I hope that helps.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload