Hi Galago,

There are several ways to do this, and it really depends on the size of your
database, and what your storage policies are.

Here are some of the various methods we have used:

   - Use ID max, then random.randint().
   Only works if you *never* delete rows from the database, and instead have
   a field called 'is_deleted', which is set to 1 each time. Great if you have
   a database with more than 100 thousand rows.
   POC: from django.db.models import Max,Count,Q,F; total_items =
   model.aggregate(Max('id'))['id__max']; random.randint(0,total_items)

   - Use .count(), then random.randint()
   Count is slow as hell depending on how many rows you have.

   - Use ORDER BY RAND() inside the SQL itself, although from what I
   remember, this wasn't great.

It really does just come down to how well your database has been designed,
how many rows you have, and what you are attempting to achieve. I would
suggest creating a script which benchmarks all these different methods
against the data you have, and see which comes out top, that's what we do,
the results are sometimes surprising :)

Hope this helps.

Cal


On Sun, Feb 20, 2011 at 10:19 PM, galago <prog...@gmail.com> wrote:

> What is the best way, to select X random rows from DB? I know that
> method: .all().order_by('?')[:X] is not good idea.
> What methods do you use?
>
> --
> 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+unsubscr...@googlegroups.com.
> For more options, visit this group at
> http://groups.google.com/group/django-users?hl=en.
>

-- 
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+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.

Reply via email to