gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 07:09:27 24 4
gpt4 key购买 nike

我有以下类(class)模型,包括教授、代码、学期季节、学期年份等

我有请求发布值:

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条件一样。请建议我如何使用多个条件执行一个查询。

编辑(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')

最佳答案

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

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 子句可以修复,因为这些列将始终在结果中返回,无论它们是否在过滤器 中。

关于django - 如何在 django 中动态过滤多个值的模型结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52178339/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com