本文介绍了我可以从Django ORM查询中删除ORDER BY吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎Django默认情况下在查询中添加了 ORDER BY 。我可以清除它吗?

It seems like Django by default adds ORDER BY to queries. Can I clear it?

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

```

推荐答案

您可以se:查询中的方法

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).
"""

示例:

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

这篇关于我可以从Django ORM查询中删除ORDER BY吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 10:34