如何在Django中动态过滤多个值的模型结果

时间:2018-09-05 06:21:23

标签: django model django-queryset

我有教授,代码,semester_season,semester_year等的课程模型

我有要求的帖子值:

coursecode = request.POST['coursecode']
courselist = request.POST['courselist']
semesteryear = request.POST['semesteryear']
semesterseason = request.POST['semesterseason']

这是我的过滤器,用于查找上述帖子值:

course_listobj = Course.objects.filter(
  code=coursecode,
  title=courselist,
  semester_year=semesteryear,
  semester_season=semesterseasonid).order_by(
    'code', 'title', 'semester_year', 'semester_season')

这是我的前端: enter image description here

如何查找一个帖子值是否为空,我的意思是在查询集中动态查找其他值

如果没有帖子值表示coursecode = None

在这里我发现如下:

if (coursecode != 'None') and (courselist == 'None' and semesteryear == 'None' and semesterseason == 'None'):
    course_listobj = Course.objects.filter(code=coursecode).order_by('code')

如需要条件则为上述倍数。 请建议我任何人如何在多个条件下进行一个查询。

编辑(if条件组合的工作代码):

    coursecode = request.POST['coursecode']
    courselist = request.POST['courselist']
    semesteryear = request.POST['semesteryear']
    semesterseason = request.POST['semesterseason']

    courses = Course.objects.all().order_by(
        'code', 'title', 'semester_year', 'semester_season')

    coursecodequery = Q(code=coursecode) if coursecode != 'None' else Q()
    courselistquery = Q(title=courselist) if courselist != 'None' else Q()
    semesteryearquery = Q(semester_year=semesteryear) if semesteryear != 'None' else Q()
    semesterseasonquery = Q(semester_season=semesterseason) if semesterseason != 'None' else Q()

    course_listobj = courses.filter(
        coursecodequery & courselistquery & semesteryearquery & semesterseasonquery
    )

    if coursecode == 'None' and courselist == 'None' and semesteryear == 'None' and semesterseason == 'None':
       messages.info(request, 'Please select all fields')

    if not course_listobj:
       messages.info(request, 'No matching courses')

1 个答案:

答案 0 :(得分:1)

您可以链接多个filter条件。例如:

courses = Course.objects.all().order_by(
  'code', 'title', 'semester_year', 'semester_season')
if coursecode != 'None':
    courses = courses.filter(code=coursecode)
if courselist != 'None':
    courses = courses.filter(title=courselist)
if semesteryear != 'None':
    courses = courses.filter(semester_year=semesteryear)
if semesterseason != 'None':
    courses = courses.filter(semester_season=semesterseason)

请注意,您的order_by子句可以固定,因为这些列将始终返回结果中,无论它们是否位于filter中。