我想写一个等同于这个SQL查询的Django查询:
SELECT * FROM user WHERE name LIKE '%danny%' AND name LIKE '%jack%' AND name LIKE '%peter%' ...
在Django
中,我有一个列表,例如:
lst=['danny','jack','peter']
如何构建Djagno queryset
过滤器?
答案 0 :(得分:4)
使用Q运算符:
queryargs = [Q(name__contains=i) for i in lst]
queryset = User.objects.filter(*queryargs)
<强>更新强>
我已经回答了这个问题,但考虑到你的第二个扩展问题,即如何获得组合
SELECT * FROM user WHERE (name LIKE '%danny%' AND name LIKE '%jack%' AND name LIKE '%peter%') OR (family LIKE '%danny%' AND family LIKE '%jack%' AND family LIKE '%peter%')
这应该有效:
from django.db.models import Q
qname = Q()
for i in lst:
qname &= Q(name__contains=i)
qfamily = Q()
for i in lst:
qfamily &= Q(family__contains=i)
queryset = Data.objects.filter(qname | qfamily)