Sent from my BlackBerry wireless device from MTN
Sent from my BlackBerry wireless device from MTN
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?
--
EXAMPLE: >>> _t = time.time(); x = map(lambda x: x, Post.objects.filter(id__gte=400000, id__lt=400500).all()); print "Took %ss"%(time.time() - _t) Took 0.0467309951782s >>> _t = time.time(); _res = map(lambda x: x, Post.objects.all()[400000:400500]); print "Took %ss"%(time.time() - _t) Took 1.05785298347s >>>
> What is the best way, to select X random rows from DB? I know that method: .all().order_by('?')[:X] is not good idea.
The best way is to push it onto the DB, using a raw query:
random_results = Table.objects.raw("SELECT * FROM table ORDER BY random() LIMIT X")
--
-- Christophe Pettus
x...@thebuild.com
Chris, please don't tell someone "this is the best way", when the solution is dependant on so many other factors (as stated in my original reply). Our answers strongly influence other peoples decisions, and "best practice" answers should only ever be given if you are 100% sure it is correct, and have personally experimented with every other possible method.
Please don't take offence to this email, I would expect someone to say the same to me if I had made a similar mistake.
On Feb 20, 2011, at 2:19 PM, galago wrote:
> What is the best way, to select X random rows from DB...
The best way is to push it onto the DB, using a raw query:
random_results = Table.objects.raw("SELECT * FROM table ORDER BY random() LIMIT X")
--
-- Christophe Pettus
x...@thebuild.com
--
You received this message because you are subscribed to the Google Groups "Django users" group....
You can do better if you have a guaranteed ordinal on the rows; otherwise, it has to do a full table scan no matter what.
>
> On Feb 20, 2011, at 2:19 PM, galago 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.
>
> The best way is to push it onto the DB, using a raw query:
>
> random_results = Table.objects.raw("SELECT * FROM table ORDER BY random() LIMIT X")
If you have lots of rows, this query is really slow as the db must build a new table for the ORDER BY.
--
Eric Chamberlain, Founder
RF.com - http://RF.com/
--