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?
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.
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.
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).
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.
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".
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With