Django 多条件查询(Q)
from app01.models import * from django.db.models import Q temp = Q() temp.connector = 'OR' temp.children.append(('server_name__icontains','mob')) Server.objects.filter(temp) temp = Q() temp.add(('server_name__icontains','mob'),'AND') temp.add(('id',2),'AND') temp.add(('id',3),'OR') Server.objects.filter(temp) __author__ = 'zhaobin022' from django.db.models import Q conditions = {} values = [ 'id','name'] con = Q() for k,v in conditions.items(): temp = Q() temp.connector = 'OR' for item in v: temp.children.append((k,item)) con.add(temp,'AND') result = Server.objects.filter(con).values(*values)
from django.db.models import Q
con = Q()
q1 = Q()
q1.connector = 'OR'
q1.children.append(('id', 1))
q1.children.append(('id', 10))
q1.children.append(('id', 9))
q2 = Q()
q2.connector = 'OR'
q2.children.append(('c1', 1))
q2.children.append(('c1', 10))
q2.children.append(('c1', 9))
con.add(q1, 'AND')
con.add(q2, 'AND')
n [24]: temp = Q()
In [25]: temp.add(('server_name__icontains','mob'),'AND')
Out[25]: ('server_name__icontains', 'mob')
In [26]: temp.add(('id',2),'AND')
Out[26]: ('id', 2)
In [27]: Server.objects.filter(temp)
Out[27]: [<Server: cy-mobile-1>]
In [28]:
In [28]: help(temp.add)
In [29]: temp = Q()
In [30]: temp.add(('server_name__icontains','mob'),'AND')
Out[30]: ('server_name__icontains', 'mob')
In [31]: temp.add(('id',2),'AND')
Out[31]: ('id', 2)
In [32]: temp.add(('id',3),'OR')
Out[32]: ('id', 3)
In [33]: Server.objects.filter(temp)
Out[33]: [<Server: cy-mobile-1>, <Server: cy-a>]