Friday, December 23, 2011

Re: Help me with this query

On Fri, 23 Dec 2011 20:16:11 +0100
Babatunde Akinyanmi <tundebabzy@gmail.com> wrote:

> I actually have a database with thousands of records from which I have
> to randomly select just 10 records from the thousands during every
> query. Because of efficiency, I use the normal select with limit query
> using a random number as offset and 200 as the limit. Next, the idea
> is to shuffle the results and use the first 10 numbers.

To randomly select 10 records from your model, you can also use

Model.objects.order_by('?')[0:10]

This translates loosely to something like this SQL statement:

SELECT … FROM … ORDER BY RANDOM() LIMIT 10

Beware that this might be an expensive and/or slow query, depending on your database backend. Unfortunately, I don't know how each database backend compares. See:

https://docs.djangoproject.com/en/1.3/ref/models/querysets/#order-by

Regards,
Sebastian.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate