2013-08-16 128 views
0

views.py過濾器使用Django過濾器從數據庫中的數據

def search(request): 
    reportlist = [] 
    loc_id = request.POST.get('location') 
    if loc_id: 
     location_list = ReportLocation.objects.filter(title=loc_id) 
     for locaton in location_list:      
      reportlist.append(locaton.report) 

forms.py

class SearchFilterForm(Form): 
    location = forms.ChoiceField(widget=forms.Select(), choices='',required=False, initial='Your name') 

    def __init__(self,user_id, *args, **kwargs): 
     super(SearchFilterForm, self).__init__(*args, **kwargs) 
     self.fields['location'] = forms.ChoiceField(choices=[('','All Location types')]+[(loc.id, str(loc.title)) for loc in Location.objects.filter(user=user_id).exclude(parent_location_id=None)]) 

models.py

class ReportLocation(models.Model): 
    report = models.ForeignKey(Report)  
    title = models.CharField('Location', max_length=200) 

如何ReportLocation場過濾標題字段與選擇的選擇。我嘗試在views.py上面的過濾器查詢,但它沒有顯示任何過濾的數據。需要幫助

+0

您的標題包含id字段?這很奇怪... –

回答

1

您的表單使用的是位置標識符的值鍵,而不是位置標題。 ChoiceFields使用選項中每個元組的第一部分作爲獲取POST的值,每個元組的第二部分只是用戶看到的選擇名稱。添加一個打印語句來檢查你的loc_id的值,你會明白我的意思。

因此,您需要查找request.POST中位置標識的位置標題。如果您ReportLocation模型有一個ForeignKey到位置,你可以這樣做

location_list = ReportLocation.objects.filter(location__id=loc_id) 

,但如果不與你的架構工作,你可能要查找標題作爲一個單獨的查詢。這是一個簡單的例子:

def search(request): 
    reportlist = [] 
    loc_id = request.POST.get('location') 
    if loc_id: 
     # This will cause an error if loc_id isn't found, 
     # it's just here as an example 
     loc_title = Location.objects.get(id=loc_id).title 
     location_list = ReportLocation.objects.filter(title=loc_title) 
     for locaton in location_list:      
      reportlist.append(locaton.report) 
+0

你的解決方案工作正常。 – user2439275