简体   繁体   English

Django中的虚拟过滤器

[英]Dummy filters in Django

How do I make a dummy filter query in Django (a filter that is always matched) and an exclude query that is never matched. 如何在Django中进行虚拟过滤器查询(始终匹配的过滤器)和从未匹配的排除查询。 The reason is because I have cases where my query is None, and in those cases I want to use a dummy filter. 原因是因为在某些情况下查询为“无”,在这种情况下我想使用虚拟过滤器。 This is the code: 这是代码:

MyModel.objects.filter(filterQuery).exclude(excludeQuery)

In cases where filterQuery or excludeQuery is None I get an error, so I want to add the following conditional before that query: 如果filterQueryexcludeQueryNone则会出现错误,因此我想在该查询之前添加以下条件:

if filterQuery == None: filterQuery = ???
if excludeQuery == None: excludeQuery = ???
MyModel.objects.filter(filterQuery).exclude(excludeQuery)

You should only filter/exclude when you need to, instead of using empty statement, do this: 仅在需要时才执行过滤/排除操作,而不是使用空语句:

found = MyModel.objects.all()
if filterQuery:
    found = found.filter(filterQuery)
if excludeQuery:
    found = found.exclude(excludeQuery)

The best way is to use a dict, particularly if you have complex filters. 最好的方法是使用字典,特别是如果您使用复杂的过滤器。

filterQuery = excludeQuery = {}

# optionally set the filters based on some logic
if 1==1:
  filterQuery['agent'] = 'John'

if 2==2:
  excludeQuery['user_id__in'] = [1, 2]

if 3==3:
  filterQuery['time__gte'] = timezone.now()

MyModel.objects.filter(**filterQuery).exclude(**excludeQuery)

You could add some ifs like Shang suggested to see if you need to apply the filter or not, but I doubt there is much of a performance loss and this is much more readable. 您可以添加一些建议,例如Shang建议,看看是否需要应用过滤器,但是我怀疑会有很多性能损失,而且可读性更高。

Another alternative to my answer above is to use Q() expressions, particularly if you need and/or logic: 我上面回答的另一个替代方法是使用Q()表达式,特别是在您需要和/或逻辑的情况下:

filterQuery = Q()

filterQuery = filterQuery | Q(agent='John')
filterQuery = filterQuery & Q(time__gte=timezone.now())

...

MyModel.objects.filter(filterQuery)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM