Python自动化之django orm之Q对象
什么是Q对象?
Encapsulates filters as objects that can then be combined logically (using
&
and|
)
关联查询
Poll.objects.get(
Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6)),
question__startswith='Who')
AND AND
def ceshi(request):
from app01 import models
from django.db.models import Q
conn = Q() # 大Q对象
q1 = Q() # 小Q对象
# 下面都是或的关系
q1.connector='OR'
q1.children.append(('id', 1))
q1.children.append(('id', 2))
q1.children.append(('id', 3))
#这个q2也是小Q
q2 = Q()
q2.connector = 'OR'
q2.children.append(('name', 'wo'))
conn.add(q1, 'AND')
print(conn)
print('------')
conn.add(q2, 'AND')
print(conn)
print(q1)
a = models.User.objects.filter(conn)
print(a.values())
return HttpResponse('ok')
结果
(AND: (OR: ('id', 1), ('id', 2), ('id', 3)))
------
(AND: (OR: ('id', 1), ('id', 2), ('id', 3)), ('name', 'wo'))
AND OR
from django.shortcuts import render, HttpResponse
from django.core.exceptions import NON_FIELD_ERRORS
# Create your views here.
from django import forms
from django.forms import fields
from django.forms import widgets
class User(forms.Form):
usertype = fields.ChoiceField(
choices=[],
widget=widgets.Select
)
def __init__(self,*args,**kwargs):
super(User,self).__init__(*args,**kwargs)
print(self.fields['usertype'])
print(type(self.fields['usertype']))
# print(dir())
def ceshi(request):
from app01 import models
from django.db.models import Q
conn = Q()
q1 = Q()
q1.connector='OR'
q1.children.append(('id', 1))
q1.children.append(('id', 2))
q1.children.append(('id', 3))
q2 = Q()
q2.connector = 'OR'
q2.children.append(('name', 'wo'))
conn.add(q1, 'AND')
print(conn)
print('------')
conn.add(q2, 'OR')
print(conn)
a = models.User.objects.filter(conn)
return HttpResponse('ok')
结果
(AND: (OR: ('id', 1), ('id', 2), ('id', 3)))
------
(OR: (AND: (OR: ('id', 1), ('id', 2), ('id', 3))), (OR: ('name', 'wo')))