我有一个有很多领域的模型。我想构建一个查询集,从预定义的字段列表中选择具有空白字段的对象。(任何字段,不是全部)
说:
fields=['a','b','c','d','e','f','g','h','i','j','k']
我可以写
model.objects.filter(Q(a==Null) | Q(b==Null) | Q(c==Null) ...
有没有更好的办法?
这个怎么样?
qObj = None
for field in fields:
newQ = Q(**{field : Null})
if qObj is None:
qObj = newQ
else:
qObj = qObj | newQ
我不喜欢qObj = None
下面的检查,但是在构建 Q 对象时我不知道有什么方法可以绕过它。但是,这Q(**{field: Null})
可能是您通常要寻找的东西。
我认为应该这样做:
query_terms = {}
for fieldname in fields:
query_terms['%s__isnull' % fieldname] = False
model.objects.exclude(**query_terms)
或者,如果您使用的是 2.7 或更高版本,请使用字典理解来构建query_terms
.
Your original query is awkward because it needs to be or'd together - if you instead exclude on the negation you can use the implicit and.
相当模糊(加上甚reduce()
至lambda
被BDFL批评),但应该工作:
from django.db.models import Q
q_result = reduce(lambda q, name: q | Q(**{name: None}), fields, Q())
然后只需使用它:
model.objects.filter(q_result)
You might want to rethink how the table is designed. Even if you succeed in finding a solution you will be slap with performance issues.
If you are using PostgreSQL, it comes with HStore.
This link will get you started, Working with the hstore data type in PostgreSQL 9.0 / 9.1 / 9.2 and this library for Django to make use of hstore, PostgreSQL HStore module integration for django orm.
Hstore is a key value store, you only store the fields with value.