在Django中查询动态数量的列的清理方式? [英] Cleaner way to query on a dynamic number of columns in Django?

查看:111
本文介绍了在Django中查询动态数量的列的清理方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的情况下,我有一些列名从表单。我想过滤,以确保它们都是正确的。以下是我目前所做的工作:

  for self in ... self'lele_data ['options']:
cars = cars .filter((op,True))

现在它工作是可能的〜40列要测试,因此它不会显示非常有效的继续查询。



有没有办法我可以将其压缩成一个过滤器查询?

解决方案

Django的查询集是懒惰的,所以你目前的做法实际上是非常有效的。在您尝试访问QuerySet中的一个字段之前,数据库将不会被击中,假设您没有编辑出一些代码,而且它实际上是这样的:

  cars = CarModel.objects.all()
在self.cleaned_data ['options']中的操作:
cars = cars .filter((op,True))

更多信息这里


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.

Is there a way I can condense this into one filter query?

解决方案

Django's query sets are lazy, so what you're currently doing is actually pretty efficient. 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:

cars = CarModel.objects.all()
for op in self.cleaned_data['options']:
    cars = cars.filter((op, True))

More information here.

这篇关于在Django中查询动态数量的列的清理方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆