简体   繁体   English

在Django中动态列查询的更简洁方法?

[英]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))

More information here . 更多信息在这里

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

相关问题 在多列上查询 DataFrame 的最简洁方法 - Most cleaner way to query a DataFrame on multiple columns 有没有一种更干净的方法来用numpy遍历矩阵的列? - Is there a cleaner way to iterate over columns of a matrix with numpy? 有没有更清洁的方法来将过滤器与Django ORM链接起来? - Is there a cleaner way to chain filters with the Django ORM? 在 django 中保存外键关系的更简洁方法 - Cleaner way to save foreign key relationship in django 是否有更简洁的方法来应用需要多个数据框列到分组数据的函数? - Is there a cleaner way to apply a function that requires multiple dataframe columns to grouped data? 要在Django中过滤数据,请为多列构建动态查询 - For filtering data in Django, build dynamic query for multiple columns 更清洁/可重用的方式为Django模型发出特定的JSON - Cleaner / reusable way to emit specific JSON for django models 是否有更清洁/更好的方法来运行此显示打印编号的代码? - Is there a cleaner/better way to run this code that shows the print number? 使列数动态 - Make the number of columns dynamic 在Django中有条件地批量更新带有动态值的查询的最佳方法 - Best way to bulk update query with dynamic values conditionally in Django
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM