2015-02-23 44 views
-1

我在我的Django應用程序中有兩個模型。第一個是Journey,第二個是ScheduleSchedule型號有Journey型號的外鍵。這些模型的模式如下。搜索Django對象order_by(child_model_field)

class Journey(models.Model): 
    pass 

class Schedule(models.Model): 
    journey=models.ForeignKey(Journey) 
    day=models.CharField(max_lenth=3, choices=days) 
    start_time=models.TimeField() 

    def __unicode__(self): 
     return self.day 

我想要做的是,當我運行查詢Journey.objects.all()應該在ORDER_BY(Schedule.start_time)返回的旅程。像Journey.objects.all()。order_by(Schedule.journey)

它可能在Django的ORM中,或者這個功能是否由django提供或我必須做一個自定義查詢來做到這一點。

指導將很可觀

+0

什麼是「節」?你沒有提到它 – 2015-02-23 14:14:28

+0

它實際上是旅程,我錯打了它 – 2015-02-23 14:32:13

回答

2

你可以嘗試這樣的:

Journey.objects.all().order_by('schedule__journey') 

查詢子模型場/反向查找的格式是這樣的:

ParentModel.objects.all().order_by('lowercase_child_modelname__fieldname)') 

詳情請查看這裏:https://docs.djangoproject.com/en/1.7/topics/db/queries/#lookups-that-span-relationships

+0

沒有它沒有工作。回溯是說'不能將關鍵字計劃解析到字段列表中。我必須通過'schedule__start_time'對它進行排序 – 2015-02-23 14:44:38

+0

如果存在拼寫錯誤,並且還要驗證'Schedule'模型是否與'Journey'具有FK關係,請在您的問題中說明。你可以按照我在這個答案中提到的格式進行反向查找,從子模型的任何字段。 – ruddra 2015-02-23 14:47:23

+0

我想你說的是'Journey'是否有'Schedule'模型的外鍵。如果我們正在獲取'Schedule'模型的對象,則此語句在相反的情況下可以是有效的。即Schedule.objects.all()。order_by(Journey__field_name) – 2015-02-23 15:03:50