如何基于POST数据进行成分查询

时间:2019-01-27 16:18:51

标签: django django-queryset

我被困住了,找不到解决此任务的方法。 我有一个包含4个字段的简单搜索表单,并且无法基于它进行复合查询。

form.py

class ViewerForm(forms.Form):
    text_search = forms.CharField(required=False)
    birthday_search = forms.DateField(required=False)
    study_from_search = forms.DateField(required=False)
    study_to_search = forms.DateField(required=False)

我试图做类似的事情,但是不能正常工作。

view.py
    def viewer(request):
        if request.method == 'POST':
            form = ViewerForm(request.POST)
            if form.is_valid:
                persons_list = Person.objects.all()
                query = []
                if len(request.POST['text_search']):
                    text = request.POST['text_search']
                    query.append(persons_list.filter(Q(fio__contains=text) | Q(sex__contains=text) | Q(mobile_number__contains=text) | Q(group__contains=text) | Q(edu_organization__contains=text)))

                if len(request.POST['text_search']):
                    birthday = request.POST['birthday_search']
                    query.append(persons_list.filter(Q(birthday_date__exact=birthday)))

                if len(request.POST['study_from_search']):
                    study_from_search = request.POST['study_from_search']
                    query.append(persons_list.filter(Q(birthday_date__exact=study_from_search)))

                if len(request.POST['study_to_search']):
                    study_to_search = request.POST['study_to_search']
                    query.append(persons_list.filter(Q(period_of_study_to__exact=study_to_search)))
                persons_list.filter(query)

如何根据POST数据进行查询,如果存在字段中的数据,则进行一些过滤。

1 个答案:

答案 0 :(得分:0)

尝试一下:

query = []
if len(request.POST['text_search']):
     text = request.POST['text_search']
     query.append(Q(fio__contains=text) | Q(sex__contains=text) | Q(mobile_number__contains=text) | Q(group__contains=text) | Q(edu_organization__contains=text))

if len(request.POST['text_search']):
    birthday = request.POST['birthday_search']
    query.append(Q(birthday_date__exact=birthday))

if len(request.POST['study_from_search']):
    study_from_search = request.POST['study_from_search']
    query.append(Q(birthday_date__exact=study_from_search))

if len(request.POST['study_to_search']):
    study_to_search = request.POST['study_to_search']
    query.append(Q(period_of_study_to__exact=study_to_search))

persons_list.filter(*query)

您需要read this。它显示了如何构成Q对象。

注意:我认为您的代码中有错别字,因为如果有text_search,并且您将birthday_datestudy_from_search匹配,那么您会进行生日搜索。

注意2:您不应该检查len(),而是检查是否设置了这样的值:

study_from_search = request.POST.get('study_from_search')
if study_from_search:
    query.append(Q(...))