[英]Cleaner way to query on a dynamic number of columns in Django?
In my case, I have a number of column names coming from a form. 就我而言,我有许多来自表单的列名。 I want to filter to make sure they're all true. 我想过滤以确保它们都是真实的。 Here's how I currently do it: 这是我目前的操作方式:
for op in self.cleaned_data['options']:
cars = cars.filter((op, True))
Now it works but there are are a possible ~40 columns to be tested and it therefore doesn't appear very efficient to keep querying. 现在它可以工作,但是可能要测试约40列,因此保持查询的效率似乎并不高。
Is there a way I can condense this into one filter query? 有没有一种方法可以将其压缩为一个过滤器查询?
Build the query as a dictionary and use the ** operator to unpack the options as keyword arguments to the filter method. 将查询构建为字典,并使用**运算符将选项作为过滤器方法的关键字参数解压缩。
op_kwargs = {}
for op in self.cleaned_data['options']:
op_kwargs[op] = True
cars = CarModel.objects.filter(**op_kwargs)
This is covered in the django documentation and has been covered on SO as well. django文档中对此进行了介绍, SO也对此进行了介绍。
Django's query sets are lazy, so what you're currently doing is actually pretty efficient. Django的查询集是惰性的,因此您当前正在执行的操作实际上非常有效。 The database won't be hit until you try to access one of the fields in the QuerySet... assuming, that is, that you didn't edit out some code, and it is effectively like this: 直到您尝试访问QuerySet中的字段之一,数据库才会被选中...假设,即您没有编辑出某些代码,并且实际上是这样的:
cars = CarModel.objects.all()
for op in self.cleaned_data['options']:
cars = cars.filter((op, True))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.