我正在django中创建一个可过滤的搜索页面,该页面允许用户根据与表单中的部分或全部要求匹配的人员来搜索数据库。因为我不知道他们会选择哪个属性
我的views.py
class SearchFilter(View):
form_class = SearchByFilter
initial = {'tattoo': False, 'scar_marks': False, 'polydactyly': False}
template_name = 'donors/donor_search_attr.html'
def get(self, request):
form = self.form_class(initial=self.initial)
args = {'form': form}
return render(request, self.template_name, args)
def post(self, request):
form = self.form_class(request.POST)
if form.is_valid():
ethnicity = form.cleaned_data['ethnicity']
skintone = form.cleaned_data['skintone']
eyecolor = form.cleaned_data['eyecolor']
haircolor = form.cleaned_data['haircolor']
body_build = form.cleaned_data['body_build']
tattoo = form.cleaned_data['tattoo']
scar_marks = form.cleaned_data['scar_marks']
polydactyly = form.cleaned_data['polydactyly']
nose = form.cleaned_data['nose']
facial = form.cleaned_data['facial']
race = form.cleaned_data['race']
academic_info = form.cleaned_data['academic_info']
blood_group = form.cleaned_data['blood_group']
genotype = form.cleaned_data['genotype']
filter_values = {'ethnicity': ethnicity, 'skintone': skintone, 'eyecolor': eyecolor, 'haircolor': haircolor,
'body_build': body_build, 'nose': nose, 'facial': facial, 'race': race, 'academic_info':
academic_info, 'blood_group': blood_group, 'genotype': genotype}
d = ['donorprofile__tattoo__name={}'.format(tattoo), 'donorprofile__scar_marks__name={}'.format(scar_marks),
'donorprofile__polydactyly__name={}'.format(polydactyly)]
for table_name, values in filter_values.items():
if values:
data_format = 'donorprofile__{}__name={}'.format(table_name, values)
d.append(data_format)
# print(d)
donors = donor.objects.filter(d)
# donors = donor.objects.filter(Q(donorprofile__ethnicity__name=ethnicity) | Q(donorprofile__skintone__name=skintone) |
# Q(donorprofile__eyecolor__name=eyecolor) | Q(donorprofile__haircolor__name=haircolor) |
# Q(donorprofile__body_build__name=body_build))
return render(request, self.template_name, {'form': form, 'donors': donors, 'filter_values': d})
答案 0 :(得分:1)
不要用kwargs创建列表。使用类似这样的内容:
values = [tattoo, scar_marks, polydactyly]
table_names = ['donorprofile__tattoo__name', 'donorprofile__scar_marks__name', 'donorprofile__polydactyly__name']
for table_name, value in filter_values.items():
if value:
data_format = 'donorprofile__{}__name'.format(table_name)
table_names.append(data_format)
values.append(value)
kwargs = dict(zip(table_names, values))
donors = donor.objects.filter(**kwargs)