2013-08-08 7 views
10

DjangoはデフォルトでクエリにORDER BYを追加するようです。それをクリアすることはできますか?Django ORMクエリから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

:クエリから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 
+0

、デフォルトのクリアを強制するかどうかを示しますモデル発注。 – aehlke

15

実際には、ちょうどquery.order_by()が十分ですか。ここで

はあなたの参考のために、order_byの実装です - あなたは `clear_ordering(真)または` `clear_ordering(偽)`のいずれかを使用する必要がDjangoの1.6では

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

残念ながら、ここでは 'force_empty = False'が重要です。モデルのデフォルトの順序はクリアされません。 – aehlke

+2

['order_by'docs](https://docs.djangoproject.com/en/1.9/ref/models/querysets/#django.db.models.query.QuerySet.order_by)do say *あなたがしなければ任意の順序をクエリに適用したい、デフォルトの順序ではなく、パラメータなしで 'order_by()'を呼び出す* – poolie

関連する問題