我正在使用Django 1.10
我有一个查询,该查询取决于接收到的参数-它取决于'job_name'是否为None:
def delete_jobs_by_age_and_name(days_ago, job_name=None):
date_to_delete_from = datetime.today() - timedelta(days=days_ago
if job_name is not None:
jobs_to_delete = AsyncJob.objects.filter(
name=job_name,
created_at__lte=date_to_delete_from
)
else:
jobs_to_delete = AsyncJob.objects.filter(created_at__lte=date_to_delete_from)
我想在一个查询中做到这一点。例如:
job_name = ANY if job_name is None
jobs_to_delete = AsyncJob.objects.filter(
name=job_name,
created_at__lte=date_to_delete_from
)
有这样的选择吗?
答案 0 :(得分:0)
您可以编写查询。
jobs_to_delete = AsyncJob.objects.filter(created_at__lte=date_to_delete_from)
if job_name is not None:
jobs_to_delete = jobs_to_delete.filter(name=job_name)
答案 1 :(得分:0)
我相信func需要返回Jobs_to_delete值。
我能想到的最短的(两行)方法是:
jobs_to_delete = AsyncJob.objects.filter(created_at__lte=date_to_delete_from)
return jobs_to_delete.filter(name=job_name) if job_name else jobs_to_delete
通过这种方式,您可以使用“内联” if语句来缩短编写的代码并使所有内容易于阅读和简单
答案 2 :(得分:0)
您可以将filter
参数作为字典进行传递,可以事先对其进行修改,因此您只需要一个filter
调用,然后在filter
调用中解压缩字典即可。像这样:
filter_kwargs = {'created_at__lte': date_to_delete_from}
if job_name is not None:
filter_kwargs['name'] = job_name
jobs_to_delete = AsyncJob.objects.filter(**filter_kwargs)