tests.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  1. from __future__ import unicode_literals
  2. import contextlib
  3. import time
  4. import unittest
  5. from datetime import date, datetime
  6. from django.core.exceptions import FieldError
  7. from django.db import connection, models
  8. from django.test import TestCase, override_settings
  9. from django.utils import timezone
  10. from .models import Author, MySQLUnixTimestamp
  11. @contextlib.contextmanager
  12. def register_lookup(field, *lookups):
  13. try:
  14. for lookup in lookups:
  15. field.register_lookup(lookup)
  16. yield
  17. finally:
  18. for lookup in lookups:
  19. field._unregister_lookup(lookup)
  20. class Div3Lookup(models.Lookup):
  21. lookup_name = 'div3'
  22. def as_sql(self, compiler, connection):
  23. lhs, params = self.process_lhs(compiler, connection)
  24. rhs, rhs_params = self.process_rhs(compiler, connection)
  25. params.extend(rhs_params)
  26. return '(%s) %%%% 3 = %s' % (lhs, rhs), params
  27. def as_oracle(self, compiler, connection):
  28. lhs, params = self.process_lhs(compiler, connection)
  29. rhs, rhs_params = self.process_rhs(compiler, connection)
  30. params.extend(rhs_params)
  31. return 'mod(%s, 3) = %s' % (lhs, rhs), params
  32. class Div3Transform(models.Transform):
  33. lookup_name = 'div3'
  34. def as_sql(self, compiler, connection):
  35. lhs, lhs_params = compiler.compile(self.lhs)
  36. return '(%s) %%%% 3' % lhs, lhs_params
  37. def as_oracle(self, compiler, connection):
  38. lhs, lhs_params = compiler.compile(self.lhs)
  39. return 'mod(%s, 3)' % lhs, lhs_params
  40. class Div3BilateralTransform(Div3Transform):
  41. bilateral = True
  42. class Mult3BilateralTransform(models.Transform):
  43. bilateral = True
  44. lookup_name = 'mult3'
  45. def as_sql(self, compiler, connection):
  46. lhs, lhs_params = compiler.compile(self.lhs)
  47. return '3 * (%s)' % lhs, lhs_params
  48. class UpperBilateralTransform(models.Transform):
  49. bilateral = True
  50. lookup_name = 'upper'
  51. def as_sql(self, compiler, connection):
  52. lhs, lhs_params = compiler.compile(self.lhs)
  53. return 'UPPER(%s)' % lhs, lhs_params
  54. class YearTransform(models.Transform):
  55. # Use a name that avoids collision with the built-in year lookup.
  56. lookup_name = 'testyear'
  57. def as_sql(self, compiler, connection):
  58. lhs_sql, params = compiler.compile(self.lhs)
  59. return connection.ops.date_extract_sql('year', lhs_sql), params
  60. @property
  61. def output_field(self):
  62. return models.IntegerField()
  63. @YearTransform.register_lookup
  64. class YearExact(models.lookups.Lookup):
  65. lookup_name = 'exact'
  66. def as_sql(self, compiler, connection):
  67. # We will need to skip the extract part, and instead go
  68. # directly with the originating field, that is self.lhs.lhs
  69. lhs_sql, lhs_params = self.process_lhs(compiler, connection, self.lhs.lhs)
  70. rhs_sql, rhs_params = self.process_rhs(compiler, connection)
  71. # Note that we must be careful so that we have params in the
  72. # same order as we have the parts in the SQL.
  73. params = lhs_params + rhs_params + lhs_params + rhs_params
  74. # We use PostgreSQL specific SQL here. Note that we must do the
  75. # conversions in SQL instead of in Python to support F() references.
  76. return ("%(lhs)s >= (%(rhs)s || '-01-01')::date "
  77. "AND %(lhs)s <= (%(rhs)s || '-12-31')::date" %
  78. {'lhs': lhs_sql, 'rhs': rhs_sql}, params)
  79. @YearTransform.register_lookup
  80. class YearLte(models.lookups.LessThanOrEqual):
  81. """
  82. The purpose of this lookup is to efficiently compare the year of the field.
  83. """
  84. def as_sql(self, compiler, connection):
  85. # Skip the YearTransform above us (no possibility for efficient
  86. # lookup otherwise).
  87. real_lhs = self.lhs.lhs
  88. lhs_sql, params = self.process_lhs(compiler, connection, real_lhs)
  89. rhs_sql, rhs_params = self.process_rhs(compiler, connection)
  90. params.extend(rhs_params)
  91. # Build SQL where the integer year is concatenated with last month
  92. # and day, then convert that to date. (We try to have SQL like:
  93. # WHERE somecol <= '2013-12-31')
  94. # but also make it work if the rhs_sql is field reference.
  95. return "%s <= (%s || '-12-31')::date" % (lhs_sql, rhs_sql), params
  96. class Exactly(models.lookups.Exact):
  97. """
  98. This lookup is used to test lookup registration.
  99. """
  100. lookup_name = 'exactly'
  101. def get_rhs_op(self, connection, rhs):
  102. return connection.operators['exact'] % rhs
  103. class SQLFuncMixin(object):
  104. def as_sql(self, compiler, connection):
  105. return '%s()', [self.name]
  106. @property
  107. def output_field(self):
  108. return CustomField()
  109. class SQLFuncLookup(SQLFuncMixin, models.Lookup):
  110. def __init__(self, name, *args, **kwargs):
  111. super(SQLFuncLookup, self).__init__(*args, **kwargs)
  112. self.name = name
  113. class SQLFuncTransform(SQLFuncMixin, models.Transform):
  114. def __init__(self, name, *args, **kwargs):
  115. super(SQLFuncTransform, self).__init__(*args, **kwargs)
  116. self.name = name
  117. class SQLFuncFactory(object):
  118. def __init__(self, key, name):
  119. self.key = key
  120. self.name = name
  121. def __call__(self, *args, **kwargs):
  122. if self.key == 'lookupfunc':
  123. return SQLFuncLookup(self.name, *args, **kwargs)
  124. return SQLFuncTransform(self.name, *args, **kwargs)
  125. class CustomField(models.TextField):
  126. def get_lookup(self, lookup_name):
  127. if lookup_name.startswith('lookupfunc_'):
  128. key, name = lookup_name.split('_', 1)
  129. return SQLFuncFactory(key, name)
  130. return super(CustomField, self).get_lookup(lookup_name)
  131. def get_transform(self, lookup_name):
  132. if lookup_name.startswith('transformfunc_'):
  133. key, name = lookup_name.split('_', 1)
  134. return SQLFuncFactory(key, name)
  135. return super(CustomField, self).get_transform(lookup_name)
  136. class CustomModel(models.Model):
  137. field = CustomField()
  138. # We will register this class temporarily in the test method.
  139. class InMonth(models.lookups.Lookup):
  140. """
  141. InMonth matches if the column's month is the same as value's month.
  142. """
  143. lookup_name = 'inmonth'
  144. def as_sql(self, compiler, connection):
  145. lhs, lhs_params = self.process_lhs(compiler, connection)
  146. rhs, rhs_params = self.process_rhs(compiler, connection)
  147. # We need to be careful so that we get the params in right
  148. # places.
  149. params = lhs_params + rhs_params + lhs_params + rhs_params
  150. return ("%s >= date_trunc('month', %s) and "
  151. "%s < date_trunc('month', %s) + interval '1 months'" %
  152. (lhs, rhs, lhs, rhs), params)
  153. class DateTimeTransform(models.Transform):
  154. lookup_name = 'as_datetime'
  155. @property
  156. def output_field(self):
  157. return models.DateTimeField()
  158. def as_sql(self, compiler, connection):
  159. lhs, params = compiler.compile(self.lhs)
  160. return 'from_unixtime({})'.format(lhs), params
  161. class LookupTests(TestCase):
  162. def test_custom_name_lookup(self):
  163. a1 = Author.objects.create(name='a1', birthdate=date(1981, 2, 16))
  164. Author.objects.create(name='a2', birthdate=date(2012, 2, 29))
  165. custom_lookup_name = 'isactually'
  166. custom_transform_name = 'justtheyear'
  167. try:
  168. models.DateField.register_lookup(YearTransform)
  169. models.DateField.register_lookup(YearTransform, custom_transform_name)
  170. YearTransform.register_lookup(Exactly)
  171. YearTransform.register_lookup(Exactly, custom_lookup_name)
  172. qs1 = Author.objects.filter(birthdate__testyear__exactly=1981)
  173. qs2 = Author.objects.filter(birthdate__justtheyear__isactually=1981)
  174. self.assertQuerysetEqual(qs1, [a1], lambda x: x)
  175. self.assertQuerysetEqual(qs2, [a1], lambda x: x)
  176. finally:
  177. YearTransform._unregister_lookup(Exactly)
  178. YearTransform._unregister_lookup(Exactly, custom_lookup_name)
  179. models.DateField._unregister_lookup(YearTransform)
  180. models.DateField._unregister_lookup(YearTransform, custom_transform_name)
  181. def test_basic_lookup(self):
  182. a1 = Author.objects.create(name='a1', age=1)
  183. a2 = Author.objects.create(name='a2', age=2)
  184. a3 = Author.objects.create(name='a3', age=3)
  185. a4 = Author.objects.create(name='a4', age=4)
  186. with register_lookup(models.IntegerField, Div3Lookup):
  187. self.assertQuerysetEqual(
  188. Author.objects.filter(age__div3=0),
  189. [a3], lambda x: x
  190. )
  191. self.assertQuerysetEqual(
  192. Author.objects.filter(age__div3=1).order_by('age'),
  193. [a1, a4], lambda x: x
  194. )
  195. self.assertQuerysetEqual(
  196. Author.objects.filter(age__div3=2),
  197. [a2], lambda x: x
  198. )
  199. self.assertQuerysetEqual(
  200. Author.objects.filter(age__div3=3),
  201. [], lambda x: x
  202. )
  203. @unittest.skipUnless(connection.vendor == 'postgresql', "PostgreSQL specific SQL used")
  204. def test_birthdate_month(self):
  205. a1 = Author.objects.create(name='a1', birthdate=date(1981, 2, 16))
  206. a2 = Author.objects.create(name='a2', birthdate=date(2012, 2, 29))
  207. a3 = Author.objects.create(name='a3', birthdate=date(2012, 1, 31))
  208. a4 = Author.objects.create(name='a4', birthdate=date(2012, 3, 1))
  209. with register_lookup(models.DateField, InMonth):
  210. self.assertQuerysetEqual(
  211. Author.objects.filter(birthdate__inmonth=date(2012, 1, 15)),
  212. [a3], lambda x: x
  213. )
  214. self.assertQuerysetEqual(
  215. Author.objects.filter(birthdate__inmonth=date(2012, 2, 1)),
  216. [a2], lambda x: x
  217. )
  218. self.assertQuerysetEqual(
  219. Author.objects.filter(birthdate__inmonth=date(1981, 2, 28)),
  220. [a1], lambda x: x
  221. )
  222. self.assertQuerysetEqual(
  223. Author.objects.filter(birthdate__inmonth=date(2012, 3, 12)),
  224. [a4], lambda x: x
  225. )
  226. self.assertQuerysetEqual(
  227. Author.objects.filter(birthdate__inmonth=date(2012, 4, 1)),
  228. [], lambda x: x
  229. )
  230. def test_div3_extract(self):
  231. with register_lookup(models.IntegerField, Div3Transform):
  232. a1 = Author.objects.create(name='a1', age=1)
  233. a2 = Author.objects.create(name='a2', age=2)
  234. a3 = Author.objects.create(name='a3', age=3)
  235. a4 = Author.objects.create(name='a4', age=4)
  236. baseqs = Author.objects.order_by('name')
  237. self.assertQuerysetEqual(
  238. baseqs.filter(age__div3=2),
  239. [a2], lambda x: x)
  240. self.assertQuerysetEqual(
  241. baseqs.filter(age__div3__lte=3),
  242. [a1, a2, a3, a4], lambda x: x)
  243. self.assertQuerysetEqual(
  244. baseqs.filter(age__div3__in=[0, 2]),
  245. [a2, a3], lambda x: x)
  246. self.assertQuerysetEqual(
  247. baseqs.filter(age__div3__in=[2, 4]),
  248. [a2], lambda x: x)
  249. self.assertQuerysetEqual(
  250. baseqs.filter(age__div3__gte=3),
  251. [], lambda x: x)
  252. self.assertQuerysetEqual(
  253. baseqs.filter(age__div3__range=(1, 2)),
  254. [a1, a2, a4], lambda x: x)
  255. class BilateralTransformTests(TestCase):
  256. def test_bilateral_upper(self):
  257. with register_lookup(models.CharField, UpperBilateralTransform):
  258. Author.objects.bulk_create([
  259. Author(name='Doe'),
  260. Author(name='doe'),
  261. Author(name='Foo'),
  262. ])
  263. self.assertQuerysetEqual(
  264. Author.objects.filter(name__upper='doe'),
  265. ["<Author: Doe>", "<Author: doe>"], ordered=False)
  266. self.assertQuerysetEqual(
  267. Author.objects.filter(name__upper__contains='f'),
  268. ["<Author: Foo>"], ordered=False)
  269. def test_bilateral_inner_qs(self):
  270. with register_lookup(models.CharField, UpperBilateralTransform):
  271. with self.assertRaises(NotImplementedError):
  272. Author.objects.filter(name__upper__in=Author.objects.values_list('name'))
  273. def test_bilateral_multi_value(self):
  274. with register_lookup(models.CharField, UpperBilateralTransform):
  275. Author.objects.bulk_create([
  276. Author(name='Foo'),
  277. Author(name='Bar'),
  278. Author(name='Ray'),
  279. ])
  280. self.assertQuerysetEqual(
  281. Author.objects.filter(name__upper__in=['foo', 'bar', 'doe']).order_by('name'),
  282. ['Bar', 'Foo'],
  283. lambda a: a.name
  284. )
  285. def test_div3_bilateral_extract(self):
  286. with register_lookup(models.IntegerField, Div3BilateralTransform):
  287. a1 = Author.objects.create(name='a1', age=1)
  288. a2 = Author.objects.create(name='a2', age=2)
  289. a3 = Author.objects.create(name='a3', age=3)
  290. a4 = Author.objects.create(name='a4', age=4)
  291. baseqs = Author.objects.order_by('name')
  292. self.assertQuerysetEqual(
  293. baseqs.filter(age__div3=2),
  294. [a2], lambda x: x)
  295. self.assertQuerysetEqual(
  296. baseqs.filter(age__div3__lte=3),
  297. [a3], lambda x: x)
  298. self.assertQuerysetEqual(
  299. baseqs.filter(age__div3__in=[0, 2]),
  300. [a2, a3], lambda x: x)
  301. self.assertQuerysetEqual(
  302. baseqs.filter(age__div3__in=[2, 4]),
  303. [a1, a2, a4], lambda x: x)
  304. self.assertQuerysetEqual(
  305. baseqs.filter(age__div3__gte=3),
  306. [a1, a2, a3, a4], lambda x: x)
  307. self.assertQuerysetEqual(
  308. baseqs.filter(age__div3__range=(1, 2)),
  309. [a1, a2, a4], lambda x: x)
  310. def test_bilateral_order(self):
  311. with register_lookup(models.IntegerField, Mult3BilateralTransform, Div3BilateralTransform):
  312. a1 = Author.objects.create(name='a1', age=1)
  313. a2 = Author.objects.create(name='a2', age=2)
  314. a3 = Author.objects.create(name='a3', age=3)
  315. a4 = Author.objects.create(name='a4', age=4)
  316. baseqs = Author.objects.order_by('name')
  317. self.assertQuerysetEqual(
  318. baseqs.filter(age__mult3__div3=42),
  319. # mult3__div3 always leads to 0
  320. [a1, a2, a3, a4], lambda x: x)
  321. self.assertQuerysetEqual(
  322. baseqs.filter(age__div3__mult3=42),
  323. [a3], lambda x: x)
  324. def test_bilateral_fexpr(self):
  325. with register_lookup(models.IntegerField, Mult3BilateralTransform):
  326. a1 = Author.objects.create(name='a1', age=1, average_rating=3.2)
  327. a2 = Author.objects.create(name='a2', age=2, average_rating=0.5)
  328. a3 = Author.objects.create(name='a3', age=3, average_rating=1.5)
  329. a4 = Author.objects.create(name='a4', age=4)
  330. baseqs = Author.objects.order_by('name')
  331. self.assertQuerysetEqual(
  332. baseqs.filter(age__mult3=models.F('age')),
  333. [a1, a2, a3, a4], lambda x: x)
  334. self.assertQuerysetEqual(
  335. # Same as age >= average_rating
  336. baseqs.filter(age__mult3__gte=models.F('average_rating')),
  337. [a2, a3], lambda x: x)
  338. @override_settings(USE_TZ=True)
  339. class DateTimeLookupTests(TestCase):
  340. @unittest.skipUnless(connection.vendor == 'mysql', "MySQL specific SQL used")
  341. def test_datetime_output_field(self):
  342. with register_lookup(models.PositiveIntegerField, DateTimeTransform):
  343. ut = MySQLUnixTimestamp.objects.create(timestamp=time.time())
  344. y2k = timezone.make_aware(datetime(2000, 1, 1))
  345. self.assertQuerysetEqual(
  346. MySQLUnixTimestamp.objects.filter(timestamp__as_datetime__gt=y2k),
  347. [ut], lambda x: x)
  348. class YearLteTests(TestCase):
  349. def setUp(self):
  350. models.DateField.register_lookup(YearTransform)
  351. self.a1 = Author.objects.create(name='a1', birthdate=date(1981, 2, 16))
  352. self.a2 = Author.objects.create(name='a2', birthdate=date(2012, 2, 29))
  353. self.a3 = Author.objects.create(name='a3', birthdate=date(2012, 1, 31))
  354. self.a4 = Author.objects.create(name='a4', birthdate=date(2012, 3, 1))
  355. def tearDown(self):
  356. models.DateField._unregister_lookup(YearTransform)
  357. @unittest.skipUnless(connection.vendor == 'postgresql', "PostgreSQL specific SQL used")
  358. def test_year_lte(self):
  359. baseqs = Author.objects.order_by('name')
  360. self.assertQuerysetEqual(
  361. baseqs.filter(birthdate__testyear__lte=2012),
  362. [self.a1, self.a2, self.a3, self.a4], lambda x: x)
  363. self.assertQuerysetEqual(
  364. baseqs.filter(birthdate__testyear=2012),
  365. [self.a2, self.a3, self.a4], lambda x: x)
  366. self.assertNotIn('BETWEEN', str(baseqs.filter(birthdate__testyear=2012).query))
  367. self.assertQuerysetEqual(
  368. baseqs.filter(birthdate__testyear__lte=2011),
  369. [self.a1], lambda x: x)
  370. # The non-optimized version works, too.
  371. self.assertQuerysetEqual(
  372. baseqs.filter(birthdate__testyear__lt=2012),
  373. [self.a1], lambda x: x)
  374. @unittest.skipUnless(connection.vendor == 'postgresql', "PostgreSQL specific SQL used")
  375. def test_year_lte_fexpr(self):
  376. self.a2.age = 2011
  377. self.a2.save()
  378. self.a3.age = 2012
  379. self.a3.save()
  380. self.a4.age = 2013
  381. self.a4.save()
  382. baseqs = Author.objects.order_by('name')
  383. self.assertQuerysetEqual(
  384. baseqs.filter(birthdate__testyear__lte=models.F('age')),
  385. [self.a3, self.a4], lambda x: x)
  386. self.assertQuerysetEqual(
  387. baseqs.filter(birthdate__testyear__lt=models.F('age')),
  388. [self.a4], lambda x: x)
  389. def test_year_lte_sql(self):
  390. # This test will just check the generated SQL for __lte. This
  391. # doesn't require running on PostgreSQL and spots the most likely
  392. # error - not running YearLte SQL at all.
  393. baseqs = Author.objects.order_by('name')
  394. self.assertIn(
  395. '<= (2011 || ', str(baseqs.filter(birthdate__testyear__lte=2011).query))
  396. self.assertIn(
  397. '-12-31', str(baseqs.filter(birthdate__testyear__lte=2011).query))
  398. def test_postgres_year_exact(self):
  399. baseqs = Author.objects.order_by('name')
  400. self.assertIn(
  401. '= (2011 || ', str(baseqs.filter(birthdate__testyear=2011).query))
  402. self.assertIn(
  403. '-12-31', str(baseqs.filter(birthdate__testyear=2011).query))
  404. def test_custom_implementation_year_exact(self):
  405. try:
  406. # Two ways to add a customized implementation for different backends:
  407. # First is MonkeyPatch of the class.
  408. def as_custom_sql(self, compiler, connection):
  409. lhs_sql, lhs_params = self.process_lhs(compiler, connection, self.lhs.lhs)
  410. rhs_sql, rhs_params = self.process_rhs(compiler, connection)
  411. params = lhs_params + rhs_params + lhs_params + rhs_params
  412. return ("%(lhs)s >= str_to_date(concat(%(rhs)s, '-01-01'), '%%%%Y-%%%%m-%%%%d') "
  413. "AND %(lhs)s <= str_to_date(concat(%(rhs)s, '-12-31'), '%%%%Y-%%%%m-%%%%d')" %
  414. {'lhs': lhs_sql, 'rhs': rhs_sql}, params)
  415. setattr(YearExact, 'as_' + connection.vendor, as_custom_sql)
  416. self.assertIn(
  417. 'concat(',
  418. str(Author.objects.filter(birthdate__testyear=2012).query))
  419. finally:
  420. delattr(YearExact, 'as_' + connection.vendor)
  421. try:
  422. # The other way is to subclass the original lookup and register the subclassed
  423. # lookup instead of the original.
  424. class CustomYearExact(YearExact):
  425. # This method should be named "as_mysql" for MySQL, "as_postgresql" for postgres
  426. # and so on, but as we don't know which DB we are running on, we need to use
  427. # setattr.
  428. def as_custom_sql(self, compiler, connection):
  429. lhs_sql, lhs_params = self.process_lhs(compiler, connection, self.lhs.lhs)
  430. rhs_sql, rhs_params = self.process_rhs(compiler, connection)
  431. params = lhs_params + rhs_params + lhs_params + rhs_params
  432. return ("%(lhs)s >= str_to_date(CONCAT(%(rhs)s, '-01-01'), '%%%%Y-%%%%m-%%%%d') "
  433. "AND %(lhs)s <= str_to_date(CONCAT(%(rhs)s, '-12-31'), '%%%%Y-%%%%m-%%%%d')" %
  434. {'lhs': lhs_sql, 'rhs': rhs_sql}, params)
  435. setattr(CustomYearExact, 'as_' + connection.vendor, CustomYearExact.as_custom_sql)
  436. YearTransform.register_lookup(CustomYearExact)
  437. self.assertIn(
  438. 'CONCAT(',
  439. str(Author.objects.filter(birthdate__testyear=2012).query))
  440. finally:
  441. YearTransform._unregister_lookup(CustomYearExact)
  442. YearTransform.register_lookup(YearExact)
  443. class TrackCallsYearTransform(YearTransform):
  444. # Use a name that avoids collision with the built-in year lookup.
  445. lookup_name = 'testyear'
  446. call_order = []
  447. def as_sql(self, compiler, connection):
  448. lhs_sql, params = compiler.compile(self.lhs)
  449. return connection.ops.date_extract_sql('year', lhs_sql), params
  450. @property
  451. def output_field(self):
  452. return models.IntegerField()
  453. def get_lookup(self, lookup_name):
  454. self.call_order.append('lookup')
  455. return super(TrackCallsYearTransform, self).get_lookup(lookup_name)
  456. def get_transform(self, lookup_name):
  457. self.call_order.append('transform')
  458. return super(TrackCallsYearTransform, self).get_transform(lookup_name)
  459. class LookupTransformCallOrderTests(TestCase):
  460. def test_call_order(self):
  461. with register_lookup(models.DateField, TrackCallsYearTransform):
  462. # junk lookup - tries lookup, then transform, then fails
  463. with self.assertRaises(FieldError):
  464. Author.objects.filter(birthdate__testyear__junk=2012)
  465. self.assertEqual(TrackCallsYearTransform.call_order,
  466. ['lookup', 'transform'])
  467. TrackCallsYearTransform.call_order = []
  468. # junk transform - tries transform only, then fails
  469. with self.assertRaises(FieldError):
  470. Author.objects.filter(birthdate__testyear__junk__more_junk=2012)
  471. self.assertEqual(TrackCallsYearTransform.call_order,
  472. ['transform'])
  473. TrackCallsYearTransform.call_order = []
  474. # Just getting the year (implied __exact) - lookup only
  475. Author.objects.filter(birthdate__testyear=2012)
  476. self.assertEqual(TrackCallsYearTransform.call_order,
  477. ['lookup'])
  478. TrackCallsYearTransform.call_order = []
  479. # Just getting the year (explicit __exact) - lookup only
  480. Author.objects.filter(birthdate__testyear__exact=2012)
  481. self.assertEqual(TrackCallsYearTransform.call_order,
  482. ['lookup'])
  483. class CustomisedMethodsTests(TestCase):
  484. def test_overridden_get_lookup(self):
  485. q = CustomModel.objects.filter(field__lookupfunc_monkeys=3)
  486. self.assertIn('monkeys()', str(q.query))
  487. def test_overridden_get_transform(self):
  488. q = CustomModel.objects.filter(field__transformfunc_banana=3)
  489. self.assertIn('banana()', str(q.query))
  490. def test_overridden_get_lookup_chain(self):
  491. q = CustomModel.objects.filter(field__transformfunc_banana__lookupfunc_elephants=3)
  492. self.assertIn('elephants()', str(q.query))
  493. def test_overridden_get_transform_chain(self):
  494. q = CustomModel.objects.filter(field__transformfunc_banana__transformfunc_pear=3)
  495. self.assertIn('pear()', str(q.query))
  496. class SubqueryTransformTests(TestCase):
  497. def test_subquery_usage(self):
  498. with register_lookup(models.IntegerField, Div3Transform):
  499. Author.objects.create(name='a1', age=1)
  500. a2 = Author.objects.create(name='a2', age=2)
  501. Author.objects.create(name='a3', age=3)
  502. Author.objects.create(name='a4', age=4)
  503. self.assertQuerysetEqual(
  504. Author.objects.order_by('name').filter(id__in=Author.objects.filter(age__div3=2)),
  505. [a2], lambda x: x)