Django : random ordering(order_by('?')) makes additional query

后端 未结 1 2087
生来不讨喜
生来不讨喜 2021-02-09 03:45

Here is sample codes in django.

[Case 1]

views.py

from sampleapp.models import SampleModel
from django.core.cache import cache

def         


        
相关标签:
1条回答
  • 2021-02-09 04:01

    .order_by performs sorting at database level.

    Here is an example. We store lasy queryset in var results. No query has been made yet:

    results = SampleModel.objects.filter(field_A="foo")
    

    Touch the results, for example, by iterating it:

    for r in results:  # here query was send to database
        # ...
    

    Now, if we'll do it again, no attempt to database will be made, as we already have this exact query:

    for r in results:  # no query send to database
        # ...
    

    But, when you apply .order_by, the query will be different. So, django has to send new request to database:

    for r in results.order_by('?'):  # new query was send to database
        # ...
    

    Solution

    When you do the query in django, and you know, that you will get all elements from that query (i.e., no OFFSET and LIMIT), then you can process those elements in python, after you get them from database.

    results = list(SampleModel.objects.filter(field_A="foo"))  # convert here queryset to list
    

    At that line query was made and you have all elements in results.

    If you need to get random order, do it in python now:

    from random import shuffle
    shuffle(results)
    

    After that, results will have random order without additional query being send to database.

    0 讨论(0)
提交回复
热议问题