Can I remove ORDER BY from a Django ORM query?

烂漫一生 提交于 2019-12-01 15:04:24
Isidoro González Guillén

You can use: clear_ordering method from query

"""Removes any ordering settings. 

If 'force_empty' is True, there will be no ordering in the resulting
query (not even the model's default).
"""

Example:

>>> from products.models import Product
>>> products = Product.objects.filter(shortdesc='falda').order_by('id')
>>> print products.query
SELECT "products_product"."id", "products_product"."shortdesc"
WHERE "products_product"."shortdesc" = falda
ORDER BY "products_product"."id" ASC
>>> products.query.clear_ordering()
>>> print products.query
SELECT "products_product"."id", "products_product"."shortdesc"
WHERE "products_product"."shortdesc" = falda

Actually, just do a query.order_by() is enough.

Here is the implementation of order_by, for your reference -

def order_by(self, *field_names):
    """
    Returns a new QuerySet instance with the ordering changed.
    """
    assert self.query.can_filter(), \
        "Cannot reorder a query once a slice has been taken."
    obj = self._clone()
    obj.query.clear_ordering(force_empty=False)
    obj.query.add_ordering(*field_names)
    return obj

Try to use .order_by('?') at the end of queryset.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!