views.py
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 :(得分:1)
您的表单使用位置ID作为其值键,而不是位置标题。 ChoiceFields在选择中使用每个元组的第一部分作为POSTed的值,每个元组的第二部分只是用户看到的选择的名称。添加打印语句以检查loc_id
的值,您将看到我的意思。
因此,您需要在request.POST
中查找位置ID的位置标题。如果您的ReportLocation模型具有ForeignKey to Location,您可以执行类似
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)