2013-08-16 130 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