'Django: How to disable ordering in model
Let's say there is a model with default ordering described in Meta class
class People(models.Model):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
middle_name = models.CharField(max_length=100)
class Meta:
ordering = (last_name, first_name)
Is there are a way to get unordered queryset
Solution 1:[1]
You can just override by simply adding .order_by()
for example:
People.objects.all().order_by()
This will make sure that Meta ordering is overridden.
Solution 2:[2]
Using an empty order_by() worked for queries with filters.
BUT asking for the .first() element was problematic and always resulted in ORDER BY. To overcome this what I did was a little bit ugly:
People.objects.all().order_by()[:1].values_list(...)[0]
This effectively removes the ORDER BY, and avoids the problem that asking for [:1][0] where it would get optimized and add it anyway. At the moment I don't know about other workarounds, but I'd love to hear them. I tried doing the above code without the values_list, but in that case Django always tried to perform the Order By.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | vikalp.sahni |
Solution 2 | Emilio |