22

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

```

4

3 回答 3

43

其实,做一个query.order_by()就够了。

这是在文档中指定的,虽然有点难找。文档说:

如果您不希望将任何排序应用于查询,即使是默认排序也不行,请不带参数调用 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
于 2014-05-11T10:47:34.080 回答
10

您可以使用: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
于 2013-09-17T07:29:48.827 回答
-4

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

于 2019-05-17T13:34:08.060 回答