2017-07-19 17 views
0

我正在尋找位於Mozilla圖書館的this tutorial。我想根據數據庫關係在admin中創建一個列表視圖。例如,我有一個Vehicle模型和一個statusUpdate模型。 Vehicle是具有許多statusUpdates的單個實例。我想要做的是選擇最新的statusUpdate(基於我創建的dateTime字段),並在列表視圖中使用這些數據。如何從一個到多個關係中獲取相關對象以在ListView中顯示並能夠過濾?

本教程中提到:

class Vehicle(models.Model): 

class statusUpdate(models.Model): 
    vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE) 

問:我怎麼可以做模型關係的列表視圖,並能夠通過領域的關係,以過濾和傳遞給視圖?

回答

2

這是我在基於類的視圖(CBV)中想要的,我對此問題的解釋並不十分清楚。

def get_context_data(self, **kwargs): 

get_context_data是一種獲取通常不是通用視圖的數據的方法。 Vehicle已經提供給View,因爲它的模型是爲它定義的,如果你想傳遞不同模型中的對象,你需要提供一個新的上下文,get_context_data就是這樣做的方法。 statusUpdate是一個帶有外鍵的模型,可用於Vehicle。下面的完整例子。

class VehicleDetail(generic.DetailView): 
    model = Vehicle 
    template_name = 'fleetdb/detail.html' 


    def get_context_data(self, **kwargs): 
     # Call the base implementation first to get a context 
     context = super(VehicleDetail, self).get_context_data(**kwargs) 
     context['updates'] = statusUpdate.objects.filter(vehicle_id=1).order_by('-dateTime')[:5] 
     return context 
0

我不認爲這完全解決了您的問題。可以用這個方法:

context['updates'] = statusUpdate.objects.filter(vehicle_id=1).order_by('-dateTime')[:5] 

這隻會導致在vehicle_id設置爲1。我與掙扎的部分是如何得到的主鍵(在你的情況下,實際vehicle_id)的StatusUpdates的列表。我發現這個解決方案:

vehicle_id = context['vehicle'].pk # <- this is the important part 
context['updates'] = statusUpdate.objects.filter(vehicle_id=vehicle_id).order_by('-dateTime')[:5] 

我發現了上下文對象,它包含已經添加的數據(此時你需要使用它之前調用超)。現在我把它寫下來似乎很明顯,但花了我數小時才明白。

Btw。我對Django和Python很新,所以對其他人來說這可能是顯而易見的,但它對我來說不是這樣。

+0

你完全正確,我發佈的代碼最終更改爲包含車輛的PK。我忘了在這裏更新代碼。硬編碼的'1'是我測試。 – dieusu

+0

進一步閱讀的好鏈接https://stackoverflow.com/questions/36950416/when-to-use-get-get-queryset-get-context-data-in-django – dieusu

+0

哦,男孩,我不想添加另一個答案。我的文本應該是一個評論。感謝您的回覆。 – AlexWerz

相關問題