Django: Fastest way to random query one record using filter

jifferent

What is the fastest way to query one record from database that is satisfy my filter query.

mydb.objects.filter(start__gte='2017-1-1', status='yes').order_by('?')[:1]

This statement will first query thousands of records and then select one, and it is very slow, but I only need one, a random one. what is the fastest one to get?

cosinepenguin

Well, I'm not sure you will be able to do exactly what you want. I was running into a similar issue a few months ago and I ended up redesigning my implementation of my backend to make it work.

Essentially, you want to make the query time shorter by having it choose a random record that fulfills both requirements (start__gte='2017-1-1', status='yes'), but like you say in order for the query to do so, it needs to filter your entire database. This means that you can cannot get a "true" random record from the database that also fulfills the filter requirements, because filtering inherently needs to look through all of your records (otherwise it wouldn't be really random, it would just be the first one it finds that fulfills your requirements).

Instead, consider putting all records that have a status='yes' in a separate relation, so that you can pull a random record from there and join with the larger relation. That would make the query time considerably faster (and it's the type of solution I implemented to get my code to work).

If you really want a random record with the correct filter information, you might need to employ some convoluted means.

You could use a custom manager in Django to have it find only one random record, something like this:

class UsersManager(models.Manager):
    def random(self):
        count = self.aggregate(count=Count('id'))['count']
        random_index = randint(0, count - 1)
        return self.all()[random_index]

class User(models.Model):
    objects = UsersManager()
    #Your fields here (whatever they are, it seems start__gte and status are some)!
    objects = UserManager()

Which you can invoke then just by using:

User.objects.random()

This could be repeated with a check in your code until it returns a random record that fulfills your requirements. I don't think this is necessarily the cleanest or programmatically correct way of implementing this, but I don't think a faster solution exists for your specific issue.

I used this site as a source for this answer, and it has a lot more solid information about using this custom random method! You'll likely have to change the custom manager to serve your own needs, but if you add the random() method to your existing custom manager it should be able to do what you need of it!

Hope it helps!

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

Fastest way to determine if record exists

分類Dev

R Fastest way to write for loop using vectorization

分類Dev

Filter nested query if no results in Django

分類Dev

How to filter a query on Django ORM

分類Dev

Filter an ArrayIngerField using Django

分類Dev

Filter record using from date and to date

分類Dev

What's the fastest way of finding a random index in a Python list, a large number of times?

分類Dev

What is the fastest way of making random selection from two dependent vectors in C++?

分類Dev

Using filter and order_by in a query

分類Dev

Django query in One to Many relationship

分類Dev

Django query in One to Many relationship

分類Dev

Django - How to query a list inside of a filter method

分類Dev

Django query filter many to many to many etc

分類Dev

to access the filter query result passed to templates in django

分類Dev

Fastest way to copy HDD

分類Dev

One query or quick way to execute sql statement

分類Dev

MVC what is the best way to edit multiple record at one go in controller

分類Dev

MySQL selecting all records and for each select separate record - in one query

分類Dev

Idiomatic way to get a random number that is different from a previous one?

分類Dev

Way to query CloudSql from Django app

分類Dev

Fastest method to filter a huge file

分類Dev

MySQL query works properly on Query Browser but not with msqli_query. Only retrieves one record

分類Dev

Fastest way to check if a file exist using standard C++/C++11/C?

分類Dev

Django using timedelta to filter results in template

分類Dev

Fastest way to decode a hexadecimal digit

分類Dev

Fastest way to iterate Pyarrow Table

分類Dev

Find duplicate images in fastest way

分類Dev

What is the fastest way to run a script?

分類Dev

Writing SQL Query, Separating One Columns Into two columns with filter

Related 関連記事

  1. 1

    Fastest way to determine if record exists

  2. 2

    R Fastest way to write for loop using vectorization

  3. 3

    Filter nested query if no results in Django

  4. 4

    How to filter a query on Django ORM

  5. 5

    Filter an ArrayIngerField using Django

  6. 6

    Filter record using from date and to date

  7. 7

    What's the fastest way of finding a random index in a Python list, a large number of times?

  8. 8

    What is the fastest way of making random selection from two dependent vectors in C++?

  9. 9

    Using filter and order_by in a query

  10. 10

    Django query in One to Many relationship

  11. 11

    Django query in One to Many relationship

  12. 12

    Django - How to query a list inside of a filter method

  13. 13

    Django query filter many to many to many etc

  14. 14

    to access the filter query result passed to templates in django

  15. 15

    Fastest way to copy HDD

  16. 16

    One query or quick way to execute sql statement

  17. 17

    MVC what is the best way to edit multiple record at one go in controller

  18. 18

    MySQL selecting all records and for each select separate record - in one query

  19. 19

    Idiomatic way to get a random number that is different from a previous one?

  20. 20

    Way to query CloudSql from Django app

  21. 21

    Fastest method to filter a huge file

  22. 22

    MySQL query works properly on Query Browser but not with msqli_query. Only retrieves one record

  23. 23

    Fastest way to check if a file exist using standard C++/C++11/C?

  24. 24

    Django using timedelta to filter results in template

  25. 25

    Fastest way to decode a hexadecimal digit

  26. 26

    Fastest way to iterate Pyarrow Table

  27. 27

    Find duplicate images in fastest way

  28. 28

    What is the fastest way to run a script?

  29. 29

    Writing SQL Query, Separating One Columns Into two columns with filter

ホットタグ

アーカイブ