2014-11-04 43 views
0

如何在不加入外鍵表的情況下訂購與外鍵列相關的模型?通過外鍵的列爲Django模型訂購而無需連接外鍵表?

舉例來說,如果我有:

class WidgetType(Model): 
    id = AutoField(primary_key=True) 
    label = CharField(max_length=16) 
    class Meta: 
     ordering = ["label"] 

class Widget(Model): 
    type = ForeignKey(WidgetType) 

怎樣才能查詢:

SELECT * FROM widgets_widget ORDER BY type_id 

如果沒有外鍵表連接?

這似乎是<fk>_id不能使用:

>>> Widget.objects.all().order_by("type_id") 
FieldError: Cannot resolve keyword 'type_id' into field. Choices are: type 

使用<fk>__id似乎加入進來,然後忽略的FK表:

>>> print Widget.objects.all().order_by("type").query 
SELECT * FROM widgets_widget 
LEFT OUTER JOIN widgets_widgettype ON … 
ORDER BY widgets_widget.type_id 

而且使用<fk>使用外資關鍵型號的默認訂購:

>>> print Widget.objects.all().order_by("type").query 
SELECT * FROM widgets_widget 
LEFT OUTER JOIN widgets_widgettype ON … 
ORDER BY widgets_widgettype.label 
+2

着Django的版本,您正在使用?看來只有django1.7提供了沒有連接的order_by功能,你可以查看[這裏](https://docs.djangoproject.com/en/dev/ref/models/querysets/#order-by) – 2014-11-04 07:32:56

+0

這是Django 1.5 。使用Django 1.7進行測試會產生相同的結果。 – 2014-11-06 18:10:03

+0

啊,是的,但它確實看起來像'.order_by(「type_id」)'將在1.7中有效! – 2014-11-06 18:11:21

回答

2

如果您是usin g Django 1.7,請參考Geo Jacob的答案 - 它包含在內。 如果不是,如果你不需要對象實例,你可以幫助自己與values()

class UserProfile(models.Model): 
    user = models.OneToOneField(User) 
    country = models.CharField(max_length=255) 


>>> qs = UserProfile.objects.all().values('user', 'country').order_by('user') 
>>> print qs.query 
SELECT `userprofiles_userprofile`.`user_id`, `userprofiles_userprofile`.`country` FROM `userprofiles_userprofile` ORDER BY `userprofiles_userprofile`.`user_id` ASC 
>>> qs 
[{'country': u'AT', 'user': 1L}, {'country': u'AT', 'user': 18L}, {'country': u'RU', 'user': 19L}, [...] 
+0

downvote有多荒謬? – schneck 2014-11-04 11:09:22

+0

將@David Wolever添加到黑名單:D – madzohan 2014-11-04 12:29:55

+0

不是我的失望,但這個答案也是不正確的。當您使用'.order_by('user')'時,將使用'User'模型的默認排序;看我的問題中的例子。 – 2014-11-06 18:06:44