title: “ django复杂查询\t\t”
tags:

  • django
    url: 1213.html
    id: 1213
    categories:
  • 后端
    date: 2018-06-18 13:27:09

介绍

django模型的objects对象中有filter、get等方法,其中可以“字段=XXX”的方式填入参数,最终构成AND关系的SQL Where子句,若需要OR或多种混合的复杂搜索需要使用Q对象。 除此以为,django还支持利用“”方式实现查找条件关键字、方式的多表连接查询。 所有查询相关的官方文档地址:查询简介查询集完整API

查找关键字

exact 精确等于 like ‘aaa’
iexact 精确等于 忽略大小写 ilike ‘aaa’
contains 包含 like ‘%aaa%’
icontains 包含 忽略大小写 ilike ‘%aaa%’,但是对于sqlite来说,contains的作用效果等同于icontains。
gt 大于
gte 大于等于
lt 小于
lte 小于等于
in 存在于一个list范围内
startswith 以…开头
istartswith 以…开头 忽略大小写
endswith 以…结尾
iendswith 以…结尾,忽略大小写
range 在…范围内
year 日期字段的年份
month 日期字段的月份
day 日期字段的日
isnull=True/False

范例:filter(name__contains=’techie’)等效于WHERE name like ‘%techie%’

连表查询

class A(models.Model):
name = models.CharField()
class B(models.Model):
aa = models.ForeignKey(A)
B.objects.filter(aanamecontains=’test’)

通过B的外键找到A中name字段包含test内容的数据

class A(models.Model):
name = models.CharField()
class B(models.Model):
aa = models.ForeignKey(A,related_name=”FAN”)
bb = models.CharField()
A.objects.filter(FAN__bb=’XXXX’)

反向查询,查询出所有(B.aa=A且B.bb=XXXX)的A实例

Q对象使用

官方文档:https://docs.djangoproject.com/en/2.0/topics/db/queries/#complex-lookups-with-q-objects 引用django.db.models.Q Q对象与SQL语句对应关系如下:

Q(question=’Who’) | Q(question=’What’)
WHERE question = ‘Who’ OR question = ‘What’

Model.objects.get(
Q(question=’Who’),
Q(pub_date=date(2005, 5, 2)) | Q(pub_date=date(2005, 5, 6))
)
SELECT * from model WHERE question = ‘Who’ AND (pub_date = ‘2005-05-02’ OR pub_date = ‘2005-05-06’)

如果有比较复杂的关系,可以像使用容器一样构造Q对象: 单一类型条件查询:

q1 = Q()
q1.connector = ‘OR’
q1.children.append((‘id’, 1))
q1.children.append((‘id’, 2))
q1.children.append((‘id’, 3))

models.Tb1.objects.filter(q1)

符合类型条件查询:

con = 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((‘status’, ‘在线’))

con.add(q1, ‘AND’)
con.add(q2, ‘AND’)

models.Tb1.objects.filter(con)

Q对象官方使用范例

https://github.com/django/django/blob/master/tests/or_lookups/tests.py

from datetime import datetime
from operator import attrgetter

from django.db.models import Q
from django.test import TestCase

from .models import Article

class OrLookupsTests(TestCase):

  1. def setUp(self):
  2. self.a1 = Article.objects.create(
  3. headline='Hello', pub_date=datetime(2005, 11, 27)
  4. ).pk
  5. self.a2 = Article.objects.create(
  6. headline='Goodbye', pub_date=datetime(2005, 11, 28)
  7. ).pk
  8. self.a3 = Article.objects.create(
  9. headline='Hello and goodbye', pub_date=datetime(2005, 11, 29)
  10. ).pk
  11. def test\_filter\_or(self):
  12. self.assertQuerysetEqual(
  13. (
  14. Article.objects.filter(headline__startswith='Hello') |
  15. Article.objects.filter(headline__startswith='Goodbye')
  16. ), \[
  17. 'Hello',
  18. 'Goodbye',
  19. 'Hello and goodbye'
  20. \],
  21. attrgetter("headline")
  22. )
  23. self.assertQuerysetEqual(
  24. Article.objects.filter(headline\_\_contains='Hello') | Article.objects.filter(headline\_\_contains='bye'), \[
  25. 'Hello',
  26. 'Goodbye',
  27. 'Hello and goodbye'
  28. \],
  29. attrgetter("headline")
  30. )
  31. self.assertQuerysetEqual(
  32. Article.objects.filter(headline\_\_iexact='Hello') | Article.objects.filter(headline\_\_contains='ood'), \[
  33. 'Hello',
  34. 'Goodbye',
  35. 'Hello and goodbye'
  36. \],
  37. attrgetter("headline")
  38. )
  39. self.assertQuerysetEqual(
  40. Article.objects.filter(Q(headline\_\_startswith='Hello') | Q(headline\_\_startswith='Goodbye')), \[
  41. 'Hello',
  42. 'Goodbye',
  43. 'Hello and goodbye'
  44. \],
  45. attrgetter("headline")
  46. )
  47. def test_stages(self):
  48. # You can shorten this syntax with code like the following, which is
  49. # especially useful if building the query in stages:
  50. articles = Article.objects.all()
  51. self.assertQuerysetEqual(
  52. articles.filter(headline\_\_startswith='Hello') & articles.filter(headline\_\_startswith='Goodbye'),
  53. \[\]
  54. )
  55. self.assertQuerysetEqual(
  56. articles.filter(headline\_\_startswith='Hello') & articles.filter(headline\_\_contains='bye'), \[
  57. 'Hello and goodbye'
  58. \],
  59. attrgetter("headline")
  60. )
  61. def test\_pk\_q(self):
  62. self.assertQuerysetEqual(
  63. Article.objects.filter(Q(pk=self.a1) | Q(pk=self.a2)), \[
  64. 'Hello',
  65. 'Goodbye'
  66. \],
  67. attrgetter("headline")
  68. )
  69. self.assertQuerysetEqual(
  70. Article.objects.filter(Q(pk=self.a1) | Q(pk=self.a2) | Q(pk=self.a3)), \[
  71. 'Hello',
  72. 'Goodbye',
  73. 'Hello and goodbye'
  74. \],
  75. attrgetter("headline"),
  76. )
  77. def test\_pk\_in(self):
  78. self.assertQuerysetEqual(
  79. Article.objects.filter(pk__in=\[self.a1, self.a2, self.a3\]), \[
  80. 'Hello',
  81. 'Goodbye',
  82. 'Hello and goodbye'
  83. \],
  84. attrgetter("headline"),
  85. )
  86. self.assertQuerysetEqual(
  87. Article.objects.filter(pk__in=(self.a1, self.a2, self.a3)), \[
  88. 'Hello',
  89. 'Goodbye',
  90. 'Hello and goodbye'
  91. \],
  92. attrgetter("headline"),
  93. )
  94. self.assertQuerysetEqual(
  95. Article.objects.filter(pk__in=\[self.a1, self.a2, self.a3, 40000\]), \[
  96. 'Hello',
  97. 'Goodbye',
  98. 'Hello and goodbye'
  99. \],
  100. attrgetter("headline"),
  101. )
  102. def test\_q\_repr(self):
  103. or_expr = Q(baz=Article(headline="Fo?"))
  104. self.assertEqual(repr(or_expr), "<Q: (AND: ('baz', <Article: Fo?>))>")
  105. negated_or = ~Q(baz=Article(headline="Fo?"))
  106. self.assertEqual(repr(negated_or), "<Q: (NOT (AND: ('baz', <Article: Fo?>)))>")
  107. def test\_q\_negated(self):
  108. # Q objects can be negated
  109. self.assertQuerysetEqual(
  110. Article.objects.filter(Q(pk=self.a1) | ~Q(pk=self.a2)), \[
  111. 'Hello',
  112. 'Hello and goodbye'
  113. \],
  114. attrgetter("headline")
  115. )
  116. self.assertQuerysetEqual(
  117. Article.objects.filter(~Q(pk=self.a1) & ~Q(pk=self.a2)), \[
  118. 'Hello and goodbye'
  119. \],
  120. attrgetter("headline"),
  121. )
  122. # This allows for more complex queries than filter() and exclude()
  123. # alone would allow
  124. self.assertQuerysetEqual(
  125. Article.objects.filter(Q(pk=self.a1) & (~Q(pk=self.a2) | Q(pk=self.a3))), \[
  126. 'Hello'
  127. \],
  128. attrgetter("headline"),
  129. )
  130. def test\_complex\_filter(self):
  131. # The 'complex_filter' method supports framework features such as
  132. # 'limit\_choices\_to' which normally take a single dictionary of lookup
  133. # arguments but need to support arbitrary queries via Q objects too.
  134. self.assertQuerysetEqual(
  135. Article.objects.complex_filter({'pk': self.a1}), \[
  136. 'Hello'
  137. \],
  138. attrgetter("headline"),
  139. )
  140. self.assertQuerysetEqual(
  141. Article.objects.complex_filter(Q(pk=self.a1) | Q(pk=self.a2)), \[
  142. 'Hello',
  143. 'Goodbye'
  144. \],
  145. attrgetter("headline"),
  146. )
  147. def test\_empty\_in(self):
  148. # Passing "in" an empty list returns no results ...
  149. self.assertQuerysetEqual(
  150. Article.objects.filter(pk__in=\[\]),
  151. \[\]
  152. )
  153. # ... but can return results if we OR it with another query.
  154. self.assertQuerysetEqual(
  155. Article.objects.filter(Q(pk\_\_in=\[\]) | Q(headline\_\_icontains='goodbye')), \[
  156. 'Goodbye',
  157. 'Hello and goodbye'
  158. \],
  159. attrgetter("headline"),
  160. )
  161. def test\_q\_and(self):
  162. # Q arg objects are ANDed
  163. self.assertQuerysetEqual(
  164. Article.objects.filter(Q(headline\_\_startswith='Hello'), Q(headline\_\_contains='bye')), \[
  165. 'Hello and goodbye'
  166. \],
  167. attrgetter("headline")
  168. )
  169. # Q arg AND order is irrelevant
  170. self.assertQuerysetEqual(
  171. Article.objects.filter(Q(headline\_\_contains='bye'), headline\_\_startswith='Hello'), \[
  172. 'Hello and goodbye'
  173. \],
  174. attrgetter("headline"),
  175. )
  176. self.assertQuerysetEqual(
  177. Article.objects.filter(Q(headline\_\_startswith='Hello') & Q(headline\_\_startswith='Goodbye')),
  178. \[\]
  179. )
  180. def test\_q\_exclude(self):
  181. self.assertQuerysetEqual(
  182. Article.objects.exclude(Q(headline__startswith='Hello')), \[
  183. 'Goodbye'
  184. \],
  185. attrgetter("headline")
  186. )
  187. def test\_other\_arg_queries(self):
  188. # Try some arg queries with operations other than filter.
  189. self.assertEqual(
  190. Article.objects.get(Q(headline\_\_startswith='Hello'), Q(headline\_\_contains='bye')).headline,
  191. 'Hello and goodbye'
  192. )
  193. self.assertEqual(
  194. Article.objects.filter(Q(headline\_\_startswith='Hello') | Q(headline\_\_contains='bye')).count(),
  195. 3
  196. )
  197. self.assertSequenceEqual(
  198. Article.objects.filter(Q(headline\_\_startswith='Hello'), Q(headline\_\_contains='bye')).values(), \[
  199. {"headline": "Hello and goodbye", "id": self.a3, "pub_date": datetime(2005, 11, 29)},
  200. \],
  201. )
  202. self.assertEqual(
  203. Article.objects.filter(Q(headline\_\_startswith='Hello')).in\_bulk(\[self.a1, self.a2\]),
  204. {self.a1: Article.objects.get(pk=self.a1)}

)

F对象使用

官方文档:https://docs.djangoproject.com/en/2.0/ref/models/expressions/#f-expressions 有关聚合、分组、F查询可看博客:django-聚合、分组、F查询和Q查询、总结