我可以从Django ORM查询中删除ORDER BY吗?

时间:2013-08-08 14:25:48

标签: django-orm

似乎Django默认情况下会向查询添加ORDER BY。我可以清除吗?

from slowstagram.models import InstagramMedia
print InstagramMedia.objects.filter().query
SELECT
  `slowstagram_instagrammedia`.`id`,
  `slowstagram_instagrammedia`.`user_id`, 
  `slowstagram_instagrammedia`.`image_url`,
  `slowstagram_instagrammedia`.`video_url`,  
  `slowstagram_instagrammedia`.`created_time`,  
  `slowstagram_instagrammedia`.`caption`, 
  `slowstagram_instagrammedia`.`filter`, 
  `slowstagram_instagrammedia`.`link`, 
  `slowstagram_instagrammedia`.`attribution_id`, 
  `slowstagram_instagrammedia`.`likes_count`, 
  `slowstagram_instagrammedia`.`type`
FROM
  `slowstagram_instagrammedia`
ORDER BY
  `slowstagram_instagrammedia`.`id`
ASC

```

3 个答案:

答案 0 :(得分:23)

实际上,只需query.order_by()即可。

以下是order_by的实施,供您参考 -

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

答案 1 :(得分:5)

您可以使用查询

中的clear_ordering方法
"""Removes any ordering settings. 

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

示例:

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

答案 2 :(得分:0)

尝试在查询集末尾使用.order_by('?')