django - 如何在查询集中动态设置 Django 过滤器

标签 django django-queryset django-orm

我正在 React 中创建一个表,从 Django 数据库中获取一些数据。
它有过滤器,我希望它们在需要时调用 API 来获取结果。

问题是我必须复制很多行,而我很确定有更好的方法来做到这一点。

这是代码的一部分:

        if ss_value and not es_value and not iv_value and not timestamp:
            queryset = DailyReport.objects.all().filter(station_departure=ss_value)
        elif not ss_value and es_value and not iv_value and not timestamp:
            queryset = DailyReport.objects.all().filter(station_arrival=es_value)
        elif not ss_value and not es_value and iv_value and not timestamp:
            queryset = DailyReport.objects.all().filter(is_virtual=iv_value)
        elif not ss_value and not es_value and not iv_value and timestamp:
            queryset = DailyReport.objects.all().filter(
                Q(timestamp__range=(min_dt, max_dt)) | Q(upload_timestamp__range=(min_dt, max_dt)))
            logger.debug(queryset)
        elif ss_value and es_value and not iv_value and not timestamp:
            queryset = DailyReport.objects.all().filter(station_departure=ss_value, station_arrival=es_value)
        elif ss_value and not es_value and iv_value and not timestamp:
            queryset = DailyReport.objects.all().filter(station_departure=ss_value, is_virtual=iv_value)

而且这种情况一直持续着。

你有什么办法可以更干净地做到这一点吗?

谢谢:)

最佳答案

您所缺少的技术与 django 关系不大,而与 Python 关系更大。

def myfunc1(arg1, arg2):
    print(arg1, arg2)

def myfunc2(arg1=None, arg2=None):
    print(arg1, arg2)

mylist = ['val1', 'val2']
mydict = {'arg1': 'val1', 'arg2': 'val2'}

假设您有上述内容:

myfunc1('val1', 'val2')
myfunc1(*mylist)

是等价的!同样:

myfunc2('val1', 'val2')
myfunc2(**mydict)

也等价!

您可以将列表传递到函数调用中,就像它们是带有单个 * 的位置参数一样,并且可以将字典作为带有双 * 的关键字参数传递

所以最终你想要做的是建立一个以下形式的事物的字典:

filter_kwargs = {
   'django_filter_kwarg_name': 'django_filter_value'
}

所以对你来说这可能是:

# build up the dictionary (or maybe you can do this off the form, request.GET, etc
filter_kwargs = {
    'station_departure': ss_value,
    'station_arrival': es_value,
    ....
}
# do something here to filter out the empty/None key/values
filter_kwargs = {key: value if value for key, value in filter_kwargs.items}
# now get the queryset
queryset = DailyReport.objects.all().filter(**filter_kwargs)


关于django - 如何在查询集中动态设置 Django 过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63053804/

相关文章:

python - nginx: [警告] 0.0.0.0:80 上的冲突服务器名称 "domain",已忽略

mysql - prefetch_related 上的 Django ORM 注释

python - Django:将带有相关对象的QuerySet转换为JSON

python - Django 过滤器查询 - 不起作用

python - Django:重复过滤查询集的最有效方法

Django 用户模型外键到公司

python - 在django中过滤带注释的列

Django + 谷歌 URL 跟踪

python - 线程启动时出现未处理的异常

python - Django Rest框架权限冲突