Having looked at this in some of my code, I have this in my template:
{{ mytable.0.pk }} {{ mytable.1.pk }} {{ mytable.0.pk }} {{ mytable.3.pk }}
And I get this output:
91596 54774 156800 23593
Odd until you find django to execute database queries is very lazy. This is what appears in my mysql log to load a single page:
SELECT `mytable`.`id` FROM `mytable` ORDER BY RAND() LIMIT 1 SELECT `mytable`.`id` FROM `mytable` ORDER BY RAND() LIMIT 1 OFFSET 1 SELECT `mytable`.`id` FROM `mytable` ORDER BY RAND() LIMIT 1 SELECT `mytable`.`id` FROM `mytable` ORDER BY RAND() LIMIT 1 OFFSET 3
Each time you use dotted notation, it executes an entire new query. I would suggest changing your code like this:
def rate(request, type): photos = list(Photo.objects.order_by('?')[:2]) c = Context({"photos": photos, "type": type}) return render_to_response("base_rate.html", c)
Since list() forces you to evaluate, it will execute the request right then and there. In addition, the data for both of these elements is already cached, so there is no reason to hit the database again. You should be good to go.
source share