如何在不同条件下进行过滤?

时间:2019-09-11 06:57:31

标签: django django-templates django-views

在这里,我试图通过选择加入日期的年,月和组织来按三个条件过滤人员。为此,我尝试了这种方法,但是它不起作用。我在这里做错了什么?

Exception Type: ValueError
Exception Value:    
invalid literal for int() with base 10: ''

我也发现我在下面针对这个问题尝试了太长时间的这种方法。如果对此有更好的解决方案,那将是一个很大的帮助

models.py

class Staff(models.Model):
    user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE, related_name='staff')
    name = models.CharField(max_length=255, blank=True, null=True)
    organization = models.ForeignKey(Organization, on_delete=models.SET_NULL, blank=True, null=True,
                                     related_name='staff')
    joined_date = models.DateField(blank=True, null=True)

views.py

def filter_staff_users(request):
    year = request.GET.get('year')
    month = request.GET.get('month')
    organization = request.GET.get('organization')
    present_year = datetime.datetime.today().year
    years_list = range(2016,present_year + 1)

    if year or month or organization:
        staffs = Staff.objects.filter(
            Q(joined_date__year=year) | Q(joined_date__month=month) | Q(organization=organization))
        return render(request, 'organization/view_staff_users.html',
                      {'years_list': years_list, 'staffs': staffs, 'year': year, 'month': month,
                       'organization': organization})
    elif year and month and organization:
        staffs = Staff.objects.filter(Q(joined_date__year=year), Q(joined_date__month=month),
                                      Q(organization=organization))
        return render(request, 'organization/view_staff_users.html',
                      {'years_list': years_list, 'staffs': staffs, 'year': year, 'month': month,
                       'organization': organization})

    elif year:
        staffs = Staff.objects.filter(joined_date__year=year)
        return render(request, 'organization/view_staff_users.html',
                      {'years_list': years_list, 'staffs': staffs, 'year': year, 'month': month,
                       'organization': organization})

    elif month:
        staffs = Staff.objects.filter(joined_date__month=month)
        return render(request, 'organization/view_staff_users.html',
                      {'years_list': years_list, 'staffs': staffs, 'year': year, 'month': month,
                       'organization': organization})

    elif organization:
        staffs = Staff.objects.filter(organization=organization)
        return render(request, 'organization/view_staff_users.html',
                      {'years_list': rangeyears_list, 'staffs': staffs, 'year': year, 'month': month,
                       'organization': organization})

    else:
        messages.info(request, 'Nothing selected to filter.')
        return redirect('organization:view_staff_users')

模板

<form action="{% url 'organization:filter_staffs' %}" class='form-inline' >

                   <select name="year">
                       <option value="">Select Year</option>
                    {% for year in years_list %}
                       <option value="{{year}}">
                       {{year}}
                       </option>
                       {% endfor %}

                   </select>
          <select  name="month" >
            <option >Select Month</option>
            <option value="01">January</option>
            #months names here

          </select>

            <select name="organization">

                       <option value="">Select Organization</option>
                 {% for organization in organizations %}
                       <option value="{{organization.pk}}">{{organization.name}}</option>
                {% endfor %}

                   </select>


        <div>
        <button type="submit" class="btn btn-info">Find Staffs</button>
        </div>

      </form>

完整追溯:

Internal Server Error: /organization/filter/all/staffs/
Traceback (most recent call last):
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "D:\VzealProjects\StaffMgmt\organization\views.py", line 321, in filter_staff_users
    Q(joined_date__year=year) | Q(joined_date__month=month) | Q(organization=organization))
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\query.py", line 844, in filter
    return self._filter_or_exclude(False, *args, **kwargs)
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\query.py", line 862, in _filter_or_exclude
    clone.query.add_q(Q(*args, **kwargs))
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\sql\query.py", line 1263, in add_q
    clause, _ = self._add_q(q_object, self.used_aliases)
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\sql\query.py", line 1281, in _add_q
    current_negated, allow_joins, split_subq)
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\sql\query.py", line 1287, in _add_q
    split_subq=split_subq,
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\sql\query.py", line 1225, in build_filter
    condition = self.build_lookup(lookups, col, value)
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\sql\query.py", line 1096, in build_lookup
    lookup = lookup_class(lhs, rhs)
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\lookups.py", line 20, in __init__
    self.rhs = self.get_prep_lookup()
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\lookups.py", line 70, in get_prep_lookup
    return self.lhs.output_field.get_prep_value(self.rhs)
  File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\fields\__init__.py", line 1807, in get_prep_value
    return int(value)
ValueError: invalid literal for int() with base 10: ''
[11/Sep/2019 12:47:31] "GET /organization/filter/all/staffs/?year=&month=Select+Month&organization= HTTP/1.1" 500 121189

2 个答案:

答案 0 :(得分:0)

您的第一个if封锁意义不大。您检查<ul> <li> <a href="#"> <span class="tag">Tag</span> <div class="date">September 2019</div> <span class="title">Text 01</span> </a> <div class="category">My category</div> </li> <li> <a href="#"> <span class="tag">Tag</span> <div class="date">Nov 2019</div> <span class="title">Text 01</span> </a> <div class="category">My category 2</div> </li> <li> <a href="#"> <span class="tag">Tag</span> <div class="date">Dec 2019</div> <span class="title">Text 01</span> </a> <div class="category">My category3</div> </li> </ul> ,即如果它们中的任何是非空的,然后使用year or month or organization对它们中的 all 进行过滤;如果其中任何一个实际上为空白,您将得到该错误。

我无法说出您在该区块中要做什么,但是考虑到要处理其他区块中的其他组合,您应该删除它。

答案 1 :(得分:0)

我遇到了类似的问题,我必须根据可用数据动态构建过滤器。我最终得到了类似于以下内容的内容:(未经测试的代码,让您有个好主意)

    filters = Q()

    if year is not None:
        filters = filters & Q(joined_date__year=year)

    if month is not None:
        filters = filters & Q(joined_date__month=month)

    if organization is not None:
        filters = filters & Q(organization=organization)

    staffs = Staff.objects.filter( filters )
    return render(request, 'organization/view_staff_users.html',
                  {'years_list': years_list, 'staffs': staffs, 'year': year, 'month': month,
                   'organization': organization})

在上面的代码中,具有值的字段将添加到filters变量中,我们将使用该变量从Staff模型中获取值。这样,您的所有情况都将得到最小化。