-1

I want to select some x % from a mysql Django model. for example if there is 1 million device id stored into the table I want to select 20% of 1 million device id. Can any one help me with this with optimised way to do it. I am looking to achieve this using Django ORM

Naga
  • 1,931
  • 4
  • 25
  • 42
  • 1
    Possible duplicate of [Simple Random Samples from a Sql database](https://stackoverflow.com/questions/249301/simple-random-samples-from-a-sql-database) – Jan Krüger Jun 09 '18 at 12:08
  • @JanKrüger Nope its not , I am looking for suggestions using Django ORM not by plane sql query. – Naga Jun 09 '18 at 12:54
  • I have done all my research then only I have asked – Naga Jun 09 '18 at 12:54
  • @JanKrüger But thanks , I will try to make some head out of the posted link – Naga Jun 09 '18 at 12:56
  • If you need something particularly efficient for a corner case like this, usually the ORM won't help you and you need to use raw SQL anyway (Django's ORM has a raw SQL feature for this). You might even be able to use a Django query expression to wrap it, but there's probably no big advantage over raw SQL. – Jan Krüger Jun 09 '18 at 12:59
  • @JanKrüger Thank you, I will try to implement. – Naga Jun 09 '18 at 13:00
  • One more thing to keep in mind: this places a lot of stress on the database server - it has to read the entire table - so don't run this query all the time. :) If you need to use the sampled data very often, create a new table containing the sampled data and work on that. You can delete and re-create the second table periodically to re-sample. – Jan Krüger Jun 09 '18 at 13:06

1 Answers1

0

if you want to use orm, i think you just request count(), and then create list of pk by using loop. and at the end you just use Model.objects.filter(pk__in=<list of pk>).