Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mix queryset results?

Tags:

django

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. How to do it?

like image 878
Nips Avatar asked Aug 22 '12 12:08

Nips


People also ask

How you combine multiple QuerySet in a view?

The SolutionThe Python union operator can be used to combine QuerySets that belong to the same model. You can also use the chain() method from the Itertools module, which allows you to combine two or more QuerySets from different models through concatenation.

How do I add one QuerySet to another?

Use union operator for queryset | to take union of two queryset. If both queryset belongs to same model / single model than it is possible to combine querysets by using union operator. One other way to achieve combine operation between two queryset is to use itertools chain function. Instead of itertools.

How do I merge two Django models?

1 Answer. Show activity on this post. In your models Device and History models are related with a foreign key from History to DeviceModel, this mean when you have a History object you can retrieve the Device model related to it, and viceversa (if you have a Device you can get its History).

What does a QuerySet return?

Returns a QuerySet that returns dictionaries, rather than model instances, when used as an iterable. Each of those dictionaries represents an object, with the keys corresponding to the attribute names of model objects.


2 Answers

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".

like image 174
AndyTheEntity Avatar answered Nov 15 '22 19:11

AndyTheEntity


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())
like image 33
Sergey Lyapustin Avatar answered Nov 15 '22 18:11

Sergey Lyapustin