How to mix queryset results?

后端 未结 3 1624
走了就别回头了
走了就别回头了 2020-12-29 09:54

I have query:

items = MyModel.objects.all().order_by(\'nr\')[:10]

and I get 10 items with higher number. Now I have to mix these results. H

相关标签:
3条回答
  • 2020-12-29 10:19

    You can't reorder a query once a slice has been taken, so use different approach

    import random
    items = sorted(MyModel.objects.all().order_by('nr')[:10], key=lambda x: random.random())
    
    0 讨论(0)
  • 2020-12-29 10:26

    OK, you can't re-order a queryset after you've pulled it in, but you can do this instead

    import random
    items = list(MyModel.objects.all().order_by('nr')[:10])
    random.shuffle(items)
    
    0 讨论(0)
  • 2020-12-29 10:32

    Curiously, this not very well documented feature works:

    Country.objects.order_by('?')
    

    source: http://www.jpstacey.info/blog/2008/09/03/random-ordering-of-query-results-in-django

    Astonishingly, the existing documentation has very little Google juice, unless you search for "randomly" rather than "random".

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