| 1 |
import time |
| 2 |
import unittest |
| 3 |
from datetime import date, datetime |
| 4 |
|
| 5 |
from django.core.exceptions import FieldError |
| 6 |
from django.db import connection, models |
| 7 |
from django.db.models.fields.related_lookups import RelatedGreaterThan |
| 8 |
from django.db.models.lookups import EndsWith, StartsWith |
| 9 |
from django.test import SimpleTestCase, TestCase, override_settings |
| 10 |
from django.test.utils import register_lookup |
| 11 |
from django.utils import timezone |
| 12 |
|
| 13 |
from .models import Article, Author, MySQLUnixTimestamp |
| 14 |
|
| 15 |
|
| 16 |
class Div3Lookup(models.Lookup): |
| 17 |
lookup_name = "div3" |
| 18 |
|
| 19 |
def as_sql(self, compiler, connection): |
| 20 |
lhs, params = self.process_lhs(compiler, connection) |
| 21 |
rhs, rhs_params = self.process_rhs(compiler, connection) |
| 22 |
params.extend(rhs_params) |
| 23 |
return "(%s) %%%% 3 = %s" % (lhs, rhs), params |
| 24 |
|
| 25 |
def as_oracle(self, compiler, connection): |
| 26 |
lhs, params = self.process_lhs(compiler, connection) |
| 27 |
rhs, rhs_params = self.process_rhs(compiler, connection) |
| 28 |
params.extend(rhs_params) |
| 29 |
return "mod(%s, 3) = %s" % (lhs, rhs), params |
| 30 |
|
| 31 |
|
| 32 |
class Div3Transform(models.Transform): |
| 33 |
lookup_name = "div3" |
| 34 |
|
| 35 |
def as_sql(self, compiler, connection): |
| 36 |
lhs, lhs_params = compiler.compile(self.lhs) |
| 37 |
return "(%s) %%%% 3" % lhs, lhs_params |
| 38 |
|
| 39 |
def as_oracle(self, compiler, connection, **extra_context): |
| 40 |
lhs, lhs_params = compiler.compile(self.lhs) |
| 41 |
return "mod(%s, 3)" % lhs, lhs_params |
| 42 |
|
| 43 |
|
| 44 |
class Div3BilateralTransform(Div3Transform): |
| 45 |
bilateral = True |
| 46 |
|
| 47 |
|
| 48 |
class Mult3BilateralTransform(models.Transform): |
| 49 |
bilateral = True |
| 50 |
lookup_name = "mult3" |
| 51 |
|
| 52 |
def as_sql(self, compiler, connection): |
| 53 |
lhs, lhs_params = compiler.compile(self.lhs) |
| 54 |
return "3 * (%s)" % lhs, lhs_params |
| 55 |
|
| 56 |
|
| 57 |
class LastDigitTransform(models.Transform): |
| 58 |
lookup_name = "lastdigit" |
| 59 |
|
| 60 |
def as_sql(self, compiler, connection): |
| 61 |
lhs, lhs_params = compiler.compile(self.lhs) |
| 62 |
return "SUBSTR(CAST(%s AS CHAR(2)), 2, 1)" % lhs, lhs_params |
| 63 |
|
| 64 |
|
| 65 |
class UpperBilateralTransform(models.Transform): |
| 66 |
bilateral = True |
| 67 |
lookup_name = "upper" |
| 68 |
|
| 69 |
def as_sql(self, compiler, connection): |
| 70 |
lhs, lhs_params = compiler.compile(self.lhs) |
| 71 |
return "UPPER(%s)" % lhs, lhs_params |
| 72 |
|
| 73 |
|
| 74 |
class YearTransform(models.Transform): |
| 75 |
# Use a name that avoids collision with the built-in year lookup. |
| 76 |
lookup_name = "testyear" |
| 77 |
|
| 78 |
def as_sql(self, compiler, connection): |
| 79 |
lhs_sql, params = compiler.compile(self.lhs) |
| 80 |
return connection.ops.date_extract_sql("year", lhs_sql, params) |
| 81 |
|
| 82 |
@property |
| 83 |
def output_field(self): |
| 84 |
return models.IntegerField() |
| 85 |
|
| 86 |
|
| 87 |
@YearTransform.register_lookup |
| 88 |
class YearExact(models.lookups.Lookup): |
| 89 |
lookup_name = "exact" |
| 90 |
|
| 91 |
def as_sql(self, compiler, connection): |
| 92 |
# We will need to skip the extract part, and instead go |
| 93 |
# directly with the originating field, that is self.lhs.lhs |
| 94 |
lhs_sql, lhs_params = self.process_lhs(compiler, connection, self.lhs.lhs) |
| 95 |
rhs_sql, rhs_params = self.process_rhs(compiler, connection) |
| 96 |
# Note that we must be careful so that we have params in the |
| 97 |
# same order as we have the parts in the SQL. |
| 98 |
params = lhs_params + rhs_params + lhs_params + rhs_params |
| 99 |
# We use PostgreSQL specific SQL here. Note that we must do the |
| 100 |
# conversions in SQL instead of in Python to support F() references. |
| 101 |
return ( |
| 102 |
"%(lhs)s >= (%(rhs)s || '-01-01')::date " |
| 103 |
"AND %(lhs)s <= (%(rhs)s || '-12-31')::date" |
| 104 |
% {"lhs": lhs_sql, "rhs": rhs_sql}, |
| 105 |
params, |
| 106 |
) |
| 107 |
|
| 108 |
|
| 109 |
@YearTransform.register_lookup |
| 110 |
class YearLte(models.lookups.LessThanOrEqual): |
| 111 |
""" |
| 112 |
The purpose of this lookup is to efficiently compare the year of the field. |
| 113 |
""" |
| 114 |
|
| 115 |
def as_sql(self, compiler, connection): |
| 116 |
# Skip the YearTransform above us (no possibility for efficient |
| 117 |
# lookup otherwise). |
| 118 |
real_lhs = self.lhs.lhs |
| 119 |
lhs_sql, params = self.process_lhs(compiler, connection, real_lhs) |
| 120 |
rhs_sql, rhs_params = self.process_rhs(compiler, connection) |
| 121 |
params.extend(rhs_params) |
| 122 |
# Build SQL where the integer year is concatenated with last month |
| 123 |
# and day, then convert that to date. (We try to have SQL like: |
| 124 |
# WHERE somecol <= '2013-12-31') |
| 125 |
# but also make it work if the rhs_sql is field reference. |
| 126 |
return "%s <= (%s || '-12-31')::date" % (lhs_sql, rhs_sql), params |
| 127 |
|
| 128 |
|
| 129 |
class Exactly(models.lookups.Exact): |
| 130 |
""" |
| 131 |
This lookup is used to test lookup registration. |
| 132 |
""" |
| 133 |
|
| 134 |
lookup_name = "exactly" |
| 135 |
|
| 136 |
def get_rhs_op(self, connection, rhs): |
| 137 |
return connection.operators["exact"] % rhs |
| 138 |
|
| 139 |
|
| 140 |
class SQLFuncMixin: |
| 141 |
def as_sql(self, compiler, connection): |
| 142 |
return "%s()" % self.name, [] |
| 143 |
|
| 144 |
@property |
| 145 |
def output_field(self): |
| 146 |
return CustomField() |
| 147 |
|
| 148 |
|
| 149 |
class SQLFuncLookup(SQLFuncMixin, models.Lookup): |
| 150 |
def __init__(self, name, *args, **kwargs): |
| 151 |
super().__init__(*args, **kwargs) |
| 152 |
self.name = name |
| 153 |
|
| 154 |
|
| 155 |
class SQLFuncTransform(SQLFuncMixin, models.Transform): |
| 156 |
def __init__(self, name, *args, **kwargs): |
| 157 |
super().__init__(*args, **kwargs) |
| 158 |
self.name = name |
| 159 |
|
| 160 |
|
| 161 |
class SQLFuncFactory: |
| 162 |
def __init__(self, key, name): |
| 163 |
self.key = key |
| 164 |
self.name = name |
| 165 |
|
| 166 |
def __call__(self, *args, **kwargs): |
| 167 |
if self.key == "lookupfunc": |
| 168 |
return SQLFuncLookup(self.name, *args, **kwargs) |
| 169 |
return SQLFuncTransform(self.name, *args, **kwargs) |
| 170 |
|
| 171 |
|
| 172 |
class CustomField(models.TextField): |
| 173 |
def get_lookup(self, lookup_name): |
| 174 |
if lookup_name.startswith("lookupfunc_"): |
| 175 |
key, name = lookup_name.split("_", 1) |
| 176 |
return SQLFuncFactory(key, name) |
| 177 |
return super().get_lookup(lookup_name) |
| 178 |
|
| 179 |
def get_transform(self, lookup_name): |
| 180 |
if lookup_name.startswith("transformfunc_"): |
| 181 |
key, name = lookup_name.split("_", 1) |
| 182 |
return SQLFuncFactory(key, name) |
| 183 |
return super().get_transform(lookup_name) |
| 184 |
|
| 185 |
|
| 186 |
class CustomModel(models.Model): |
| 187 |
field = CustomField() |
| 188 |
|
| 189 |
|
| 190 |
# We will register this class temporarily in the test method. |
| 191 |
|
| 192 |
|
| 193 |
class InMonth(models.lookups.Lookup): |
| 194 |
""" |
| 195 |
InMonth matches if the column's month is the same as value's month. |
| 196 |
""" |
| 197 |
|
| 198 |
lookup_name = "inmonth" |
| 199 |
|
| 200 |
def as_sql(self, compiler, connection): |
| 201 |
lhs, lhs_params = self.process_lhs(compiler, connection) |
| 202 |
rhs, rhs_params = self.process_rhs(compiler, connection) |
| 203 |
# We need to be careful so that we get the params in right |
| 204 |
# places. |
| 205 |
params = lhs_params + rhs_params + lhs_params + rhs_params |
| 206 |
return ( |
| 207 |
"%s >= date_trunc('month', %s) and " |
| 208 |
"%s < date_trunc('month', %s) + interval '1 months'" % (lhs, rhs, lhs, rhs), |
| 209 |
params, |
| 210 |
) |
| 211 |
|
| 212 |
|
| 213 |
class DateTimeTransform(models.Transform): |
| 214 |
lookup_name = "as_datetime" |
| 215 |
|
| 216 |
@property |
| 217 |
def output_field(self): |
| 218 |
return models.DateTimeField() |
| 219 |
|
| 220 |
def as_sql(self, compiler, connection): |
| 221 |
lhs, params = compiler.compile(self.lhs) |
| 222 |
return "from_unixtime({})".format(lhs), params |
| 223 |
|
| 224 |
|
| 225 |
class CustomStartsWith(StartsWith): |
| 226 |
lookup_name = "sw" |
| 227 |
|
| 228 |
|
| 229 |
class CustomEndsWith(EndsWith): |
| 230 |
lookup_name = "ew" |
| 231 |
|
| 232 |
|
| 233 |
class RelatedMoreThan(RelatedGreaterThan): |
| 234 |
lookup_name = "rmt" |
| 235 |
|
| 236 |
|
| 237 |
class LookupTests(TestCase): |
| 238 |
def test_custom_name_lookup(self): |
| 239 |
a1 = Author.objects.create(name="a1", birthdate=date(1981, 2, 16)) |
| 240 |
Author.objects.create(name="a2", birthdate=date(2012, 2, 29)) |
| 241 |
with ( |
| 242 |
register_lookup(models.DateField, YearTransform), |
| 243 |
register_lookup(models.DateField, YearTransform, lookup_name="justtheyear"), |
| 244 |
register_lookup(YearTransform, Exactly), |
| 245 |
register_lookup(YearTransform, Exactly, lookup_name="isactually"), |
| 246 |
): |
| 247 |
qs1 = Author.objects.filter(birthdate__testyear__exactly=1981) |
| 248 |
qs2 = Author.objects.filter(birthdate__justtheyear__isactually=1981) |
| 249 |
self.assertSequenceEqual(qs1, [a1]) |
| 250 |
self.assertSequenceEqual(qs2, [a1]) |
| 251 |
|
| 252 |
def test_custom_exact_lookup_none_rhs(self): |
| 253 |
""" |
| 254 |
__exact=None is transformed to __isnull=True if a custom lookup class |
| 255 |
with lookup_name != 'exact' is registered as the `exact` lookup. |
| 256 |
""" |
| 257 |
field = Author._meta.get_field("birthdate") |
| 258 |
OldExactLookup = field.get_lookup("exact") |
| 259 |
author = Author.objects.create(name="author", birthdate=None) |
| 260 |
try: |
| 261 |
field.register_lookup(Exactly, "exact") |
| 262 |
self.assertEqual(Author.objects.get(birthdate__exact=None), author) |
| 263 |
finally: |
| 264 |
field.register_lookup(OldExactLookup, "exact") |
| 265 |
|
| 266 |
def test_basic_lookup(self): |
| 267 |
a1 = Author.objects.create(name="a1", age=1) |
| 268 |
a2 = Author.objects.create(name="a2", age=2) |
| 269 |
a3 = Author.objects.create(name="a3", age=3) |
| 270 |
a4 = Author.objects.create(name="a4", age=4) |
| 271 |
with register_lookup(models.IntegerField, Div3Lookup): |
| 272 |
self.assertSequenceEqual(Author.objects.filter(age__div3=0), [a3]) |
| 273 |
self.assertSequenceEqual( |
| 274 |
Author.objects.filter(age__div3=1).order_by("age"), [a1, a4] |
| 275 |
) |
| 276 |
self.assertSequenceEqual(Author.objects.filter(age__div3=2), [a2]) |
| 277 |
self.assertSequenceEqual(Author.objects.filter(age__div3=3), []) |
| 278 |
|
| 279 |
@unittest.skipUnless( |
| 280 |
connection.vendor == "postgresql", "PostgreSQL specific SQL used" |
| 281 |
) |
| 282 |
def test_birthdate_month(self): |
| 283 |
a1 = Author.objects.create(name="a1", birthdate=date(1981, 2, 16)) |
| 284 |
a2 = Author.objects.create(name="a2", birthdate=date(2012, 2, 29)) |
| 285 |
a3 = Author.objects.create(name="a3", birthdate=date(2012, 1, 31)) |
| 286 |
a4 = Author.objects.create(name="a4", birthdate=date(2012, 3, 1)) |
| 287 |
with register_lookup(models.DateField, InMonth): |
| 288 |
self.assertSequenceEqual( |
| 289 |
Author.objects.filter(birthdate__inmonth=date(2012, 1, 15)), [a3] |
| 290 |
) |
| 291 |
self.assertSequenceEqual( |
| 292 |
Author.objects.filter(birthdate__inmonth=date(2012, 2, 1)), [a2] |
| 293 |
) |
| 294 |
self.assertSequenceEqual( |
| 295 |
Author.objects.filter(birthdate__inmonth=date(1981, 2, 28)), [a1] |
| 296 |
) |
| 297 |
self.assertSequenceEqual( |
| 298 |
Author.objects.filter(birthdate__inmonth=date(2012, 3, 12)), [a4] |
| 299 |
) |
| 300 |
self.assertSequenceEqual( |
| 301 |
Author.objects.filter(birthdate__inmonth=date(2012, 4, 1)), [] |
| 302 |
) |
| 303 |
|
| 304 |
def test_div3_extract(self): |
| 305 |
with register_lookup(models.IntegerField, Div3Transform): |
| 306 |
a1 = Author.objects.create(name="a1", age=1) |
| 307 |
a2 = Author.objects.create(name="a2", age=2) |
| 308 |
a3 = Author.objects.create(name="a3", age=3) |
| 309 |
a4 = Author.objects.create(name="a4", age=4) |
| 310 |
baseqs = Author.objects.order_by("name") |
| 311 |
self.assertSequenceEqual(baseqs.filter(age__div3=2), [a2]) |
| 312 |
self.assertSequenceEqual(baseqs.filter(age__div3__lte=3), [a1, a2, a3, a4]) |
| 313 |
self.assertSequenceEqual(baseqs.filter(age__div3__in=[0, 2]), [a2, a3]) |
| 314 |
self.assertSequenceEqual(baseqs.filter(age__div3__in=[2, 4]), [a2]) |
| 315 |
self.assertSequenceEqual(baseqs.filter(age__div3__gte=3), []) |
| 316 |
self.assertSequenceEqual( |
| 317 |
baseqs.filter(age__div3__range=(1, 2)), [a1, a2, a4] |
| 318 |
) |
| 319 |
|
| 320 |
def test_foreignobject_lookup_registration(self): |
| 321 |
field = Article._meta.get_field("author") |
| 322 |
|
| 323 |
with register_lookup(models.ForeignObject, Exactly): |
| 324 |
self.assertIs(field.get_lookup("exactly"), Exactly) |
| 325 |
|
| 326 |
# ForeignObject should ignore regular Field lookups |
| 327 |
with register_lookup(models.Field, Exactly): |
| 328 |
self.assertIsNone(field.get_lookup("exactly")) |
| 329 |
|
| 330 |
def test_lookups_caching(self): |
| 331 |
field = Article._meta.get_field("author") |
| 332 |
|
| 333 |
# clear and re-cache |
| 334 |
field.get_class_lookups.cache_clear() |
| 335 |
self.assertNotIn("exactly", field.get_lookups()) |
| 336 |
|
| 337 |
# registration should bust the cache |
| 338 |
with register_lookup(models.ForeignObject, Exactly): |
| 339 |
# getting the lookups again should re-cache |
| 340 |
self.assertIn("exactly", field.get_lookups()) |
| 341 |
# Unregistration should bust the cache. |
| 342 |
self.assertNotIn("exactly", field.get_lookups()) |
| 343 |
|
| 344 |
|
| 345 |
class BilateralTransformTests(TestCase): |
| 346 |
def test_bilateral_upper(self): |
| 347 |
with register_lookup(models.CharField, UpperBilateralTransform): |
| 348 |
author1 = Author.objects.create(name="Doe") |
| 349 |
author2 = Author.objects.create(name="doe") |
| 350 |
author3 = Author.objects.create(name="Foo") |
| 351 |
self.assertCountEqual( |
| 352 |
Author.objects.filter(name__upper="doe"), |
| 353 |
[author1, author2], |
| 354 |
) |
| 355 |
self.assertSequenceEqual( |
| 356 |
Author.objects.filter(name__upper__contains="f"), |
| 357 |
[author3], |
| 358 |
) |
| 359 |
|
| 360 |
def test_bilateral_inner_qs(self): |
| 361 |
with register_lookup(models.CharField, UpperBilateralTransform): |
| 362 |
msg = "Bilateral transformations on nested querysets are not implemented." |
| 363 |
with self.assertRaisesMessage(NotImplementedError, msg): |
| 364 |
Author.objects.filter( |
| 365 |
name__upper__in=Author.objects.values_list("name") |
| 366 |
) |
| 367 |
|
| 368 |
def test_bilateral_multi_value(self): |
| 369 |
with register_lookup(models.CharField, UpperBilateralTransform): |
| 370 |
Author.objects.bulk_create( |
| 371 |
[ |
| 372 |
Author(name="Foo"), |
| 373 |
Author(name="Bar"), |
| 374 |
Author(name="Ray"), |
| 375 |
] |
| 376 |
) |
| 377 |
self.assertQuerySetEqual( |
| 378 |
Author.objects.filter(name__upper__in=["foo", "bar", "doe"]).order_by( |
| 379 |
"name" |
| 380 |
), |
| 381 |
["Bar", "Foo"], |
| 382 |
lambda a: a.name, |
| 383 |
) |
| 384 |
|
| 385 |
def test_div3_bilateral_extract(self): |
| 386 |
with register_lookup(models.IntegerField, Div3BilateralTransform): |
| 387 |
a1 = Author.objects.create(name="a1", age=1) |
| 388 |
a2 = Author.objects.create(name="a2", age=2) |
| 389 |
a3 = Author.objects.create(name="a3", age=3) |
| 390 |
a4 = Author.objects.create(name="a4", age=4) |
| 391 |
baseqs = Author.objects.order_by("name") |
| 392 |
self.assertSequenceEqual(baseqs.filter(age__div3=2), [a2]) |
| 393 |
self.assertSequenceEqual(baseqs.filter(age__div3__lte=3), [a3]) |
| 394 |
self.assertSequenceEqual(baseqs.filter(age__div3__in=[0, 2]), [a2, a3]) |
| 395 |
self.assertSequenceEqual(baseqs.filter(age__div3__in=[2, 4]), [a1, a2, a4]) |
| 396 |
self.assertSequenceEqual(baseqs.filter(age__div3__gte=3), [a1, a2, a3, a4]) |
| 397 |
self.assertSequenceEqual( |
| 398 |
baseqs.filter(age__div3__range=(1, 2)), [a1, a2, a4] |
| 399 |
) |
| 400 |
|
| 401 |
def test_bilateral_order(self): |
| 402 |
with register_lookup( |
| 403 |
models.IntegerField, Mult3BilateralTransform, Div3BilateralTransform |
| 404 |
): |
| 405 |
a1 = Author.objects.create(name="a1", age=1) |
| 406 |
a2 = Author.objects.create(name="a2", age=2) |
| 407 |
a3 = Author.objects.create(name="a3", age=3) |
| 408 |
a4 = Author.objects.create(name="a4", age=4) |
| 409 |
baseqs = Author.objects.order_by("name") |
| 410 |
|
| 411 |
# mult3__div3 always leads to 0 |
| 412 |
self.assertSequenceEqual( |
| 413 |
baseqs.filter(age__mult3__div3=42), [a1, a2, a3, a4] |
| 414 |
) |
| 415 |
self.assertSequenceEqual(baseqs.filter(age__div3__mult3=42), [a3]) |
| 416 |
|
| 417 |
def test_transform_order_by(self): |
| 418 |
with register_lookup(models.IntegerField, LastDigitTransform): |
| 419 |
a1 = Author.objects.create(name="a1", age=11) |
| 420 |
a2 = Author.objects.create(name="a2", age=23) |
| 421 |
a3 = Author.objects.create(name="a3", age=32) |
| 422 |
a4 = Author.objects.create(name="a4", age=40) |
| 423 |
qs = Author.objects.order_by("age__lastdigit") |
| 424 |
self.assertSequenceEqual(qs, [a4, a1, a3, a2]) |
| 425 |
|
| 426 |
def test_bilateral_fexpr(self): |
| 427 |
with register_lookup(models.IntegerField, Mult3BilateralTransform): |
| 428 |
a1 = Author.objects.create(name="a1", age=1, average_rating=3.2) |
| 429 |
a2 = Author.objects.create(name="a2", age=2, average_rating=0.5) |
| 430 |
a3 = Author.objects.create(name="a3", age=3, average_rating=1.5) |
| 431 |
a4 = Author.objects.create(name="a4", age=4) |
| 432 |
baseqs = Author.objects.order_by("name") |
| 433 |
self.assertSequenceEqual( |
| 434 |
baseqs.filter(age__mult3=models.F("age")), [a1, a2, a3, a4] |
| 435 |
) |
| 436 |
# Same as age >= average_rating |
| 437 |
self.assertSequenceEqual( |
| 438 |
baseqs.filter(age__mult3__gte=models.F("average_rating")), [a2, a3] |
| 439 |
) |
| 440 |
|
| 441 |
|
| 442 |
@override_settings(USE_TZ=True) |
| 443 |
class DateTimeLookupTests(TestCase): |
| 444 |
@unittest.skipUnless(connection.vendor == "mysql", "MySQL specific SQL used") |
| 445 |
def test_datetime_output_field(self): |
| 446 |
with register_lookup(models.PositiveIntegerField, DateTimeTransform): |
| 447 |
ut = MySQLUnixTimestamp.objects.create(timestamp=time.time()) |
| 448 |
y2k = timezone.make_aware(datetime(2000, 1, 1)) |
| 449 |
self.assertSequenceEqual( |
| 450 |
MySQLUnixTimestamp.objects.filter(timestamp__as_datetime__gt=y2k), [ut] |
| 451 |
) |
| 452 |
|
| 453 |
|
| 454 |
class YearLteTests(TestCase): |
| 455 |
@classmethod |
| 456 |
def setUpTestData(cls): |
| 457 |
cls.a1 = Author.objects.create(name="a1", birthdate=date(1981, 2, 16)) |
| 458 |
cls.a2 = Author.objects.create(name="a2", birthdate=date(2012, 2, 29)) |
| 459 |
cls.a3 = Author.objects.create(name="a3", birthdate=date(2012, 1, 31)) |
| 460 |
cls.a4 = Author.objects.create(name="a4", birthdate=date(2012, 3, 1)) |
| 461 |
|
| 462 |
def setUp(self): |
| 463 |
models.DateField.register_lookup(YearTransform) |
| 464 |
self.addCleanup(models.DateField._unregister_lookup, YearTransform) |
| 465 |
|
| 466 |
@unittest.skipUnless( |
| 467 |
connection.vendor == "postgresql", "PostgreSQL specific SQL used" |
| 468 |
) |
| 469 |
def test_year_lte(self): |
| 470 |
baseqs = Author.objects.order_by("name") |
| 471 |
self.assertSequenceEqual( |
| 472 |
baseqs.filter(birthdate__testyear__lte=2012), |
| 473 |
[self.a1, self.a2, self.a3, self.a4], |
| 474 |
) |
| 475 |
self.assertSequenceEqual( |
| 476 |
baseqs.filter(birthdate__testyear=2012), [self.a2, self.a3, self.a4] |
| 477 |
) |
| 478 |
|
| 479 |
self.assertNotIn("BETWEEN", str(baseqs.filter(birthdate__testyear=2012).query)) |
| 480 |
self.assertSequenceEqual( |
| 481 |
baseqs.filter(birthdate__testyear__lte=2011), [self.a1] |
| 482 |
) |
| 483 |
# The non-optimized version works, too. |
| 484 |
self.assertSequenceEqual(baseqs.filter(birthdate__testyear__lt=2012), [self.a1]) |
| 485 |
|
| 486 |
@unittest.skipUnless( |
| 487 |
connection.vendor == "postgresql", "PostgreSQL specific SQL used" |
| 488 |
) |
| 489 |
def test_year_lte_fexpr(self): |
| 490 |
self.a2.age = 2011 |
| 491 |
self.a2.save() |
| 492 |
self.a3.age = 2012 |
| 493 |
self.a3.save() |
| 494 |
self.a4.age = 2013 |
| 495 |
self.a4.save() |
| 496 |
baseqs = Author.objects.order_by("name") |
| 497 |
self.assertSequenceEqual( |
| 498 |
baseqs.filter(birthdate__testyear__lte=models.F("age")), [self.a3, self.a4] |
| 499 |
) |
| 500 |
self.assertSequenceEqual( |
| 501 |
baseqs.filter(birthdate__testyear__lt=models.F("age")), [self.a4] |
| 502 |
) |
| 503 |
|
| 504 |
def test_year_lte_sql(self): |
| 505 |
# This test will just check the generated SQL for __lte. This |
| 506 |
# doesn't require running on PostgreSQL and spots the most likely |
| 507 |
# error - not running YearLte SQL at all. |
| 508 |
baseqs = Author.objects.order_by("name") |
| 509 |
self.assertIn( |
| 510 |
"<= (2011 || ", str(baseqs.filter(birthdate__testyear__lte=2011).query) |
| 511 |
) |
| 512 |
self.assertIn("-12-31", str(baseqs.filter(birthdate__testyear__lte=2011).query)) |
| 513 |
|
| 514 |
def test_postgres_year_exact(self): |
| 515 |
baseqs = Author.objects.order_by("name") |
| 516 |
self.assertIn("= (2011 || ", str(baseqs.filter(birthdate__testyear=2011).query)) |
| 517 |
self.assertIn("-12-31", str(baseqs.filter(birthdate__testyear=2011).query)) |
| 518 |
|
| 519 |
def test_custom_implementation_year_exact(self): |
| 520 |
try: |
| 521 |
# Two ways to add a customized implementation for different backends: |
| 522 |
# First is MonkeyPatch of the class. |
| 523 |
def as_custom_sql(self, compiler, connection): |
| 524 |
lhs_sql, lhs_params = self.process_lhs( |
| 525 |
compiler, connection, self.lhs.lhs |
| 526 |
) |
| 527 |
rhs_sql, rhs_params = self.process_rhs(compiler, connection) |
| 528 |
params = lhs_params + rhs_params + lhs_params + rhs_params |
| 529 |
return ( |
| 530 |
"%(lhs)s >= " |
| 531 |
"str_to_date(concat(%(rhs)s, '-01-01'), '%%%%Y-%%%%m-%%%%d') " |
| 532 |
"AND %(lhs)s <= " |
| 533 |
"str_to_date(concat(%(rhs)s, '-12-31'), '%%%%Y-%%%%m-%%%%d')" |
| 534 |
% {"lhs": lhs_sql, "rhs": rhs_sql}, |
| 535 |
params, |
| 536 |
) |
| 537 |
|
| 538 |
setattr(YearExact, "as_" + connection.vendor, as_custom_sql) |
| 539 |
self.assertIn( |
| 540 |
"concat(", str(Author.objects.filter(birthdate__testyear=2012).query) |
| 541 |
) |
| 542 |
finally: |
| 543 |
delattr(YearExact, "as_" + connection.vendor) |
| 544 |
try: |
| 545 |
# The other way is to subclass the original lookup and register the |
| 546 |
# subclassed lookup instead of the original. |
| 547 |
class CustomYearExact(YearExact): |
| 548 |
# This method should be named "as_mysql" for MySQL, |
| 549 |
# "as_postgresql" for postgres and so on, but as we don't know |
| 550 |
# which DB we are running on, we need to use setattr. |
| 551 |
def as_custom_sql(self, compiler, connection): |
| 552 |
lhs_sql, lhs_params = self.process_lhs( |
| 553 |
compiler, connection, self.lhs.lhs |
| 554 |
) |
| 555 |
rhs_sql, rhs_params = self.process_rhs(compiler, connection) |
| 556 |
params = lhs_params + rhs_params + lhs_params + rhs_params |
| 557 |
return ( |
| 558 |
"%(lhs)s >= " |
| 559 |
"str_to_date(CONCAT(%(rhs)s, '-01-01'), '%%%%Y-%%%%m-%%%%d') " |
| 560 |
"AND %(lhs)s <= " |
| 561 |
"str_to_date(CONCAT(%(rhs)s, '-12-31'), '%%%%Y-%%%%m-%%%%d')" |
| 562 |
% {"lhs": lhs_sql, "rhs": rhs_sql}, |
| 563 |
params, |
| 564 |
) |
| 565 |
|
| 566 |
setattr( |
| 567 |
CustomYearExact, |
| 568 |
"as_" + connection.vendor, |
| 569 |
CustomYearExact.as_custom_sql, |
| 570 |
) |
| 571 |
YearTransform.register_lookup(CustomYearExact) |
| 572 |
self.assertIn( |
| 573 |
"CONCAT(", str(Author.objects.filter(birthdate__testyear=2012).query) |
| 574 |
) |
| 575 |
finally: |
| 576 |
YearTransform._unregister_lookup(CustomYearExact) |
| 577 |
YearTransform.register_lookup(YearExact) |
| 578 |
|
| 579 |
|
| 580 |
class TrackCallsYearTransform(YearTransform): |
| 581 |
# Use a name that avoids collision with the built-in year lookup. |
| 582 |
lookup_name = "testyear" |
| 583 |
call_order = [] |
| 584 |
|
| 585 |
def as_sql(self, compiler, connection): |
| 586 |
lhs_sql, params = compiler.compile(self.lhs) |
| 587 |
return connection.ops.date_extract_sql("year", lhs_sql), params |
| 588 |
|
| 589 |
@property |
| 590 |
def output_field(self): |
| 591 |
return models.IntegerField() |
| 592 |
|
| 593 |
def get_lookup(self, lookup_name): |
| 594 |
self.call_order.append("lookup") |
| 595 |
return super().get_lookup(lookup_name) |
| 596 |
|
| 597 |
def get_transform(self, lookup_name): |
| 598 |
self.call_order.append("transform") |
| 599 |
return super().get_transform(lookup_name) |
| 600 |
|
| 601 |
|
| 602 |
class LookupTransformCallOrderTests(SimpleTestCase): |
| 603 |
def test_call_order(self): |
| 604 |
with register_lookup(models.DateField, TrackCallsYearTransform): |
| 605 |
# junk lookup - tries lookup, then transform, then fails |
| 606 |
msg = ( |
| 607 |
"Unsupported lookup 'junk' for IntegerField or join on the field not " |
| 608 |
"permitted." |
| 609 |
) |
| 610 |
with self.assertRaisesMessage(FieldError, msg): |
| 611 |
Author.objects.filter(birthdate__testyear__junk=2012) |
| 612 |
self.assertEqual( |
| 613 |
TrackCallsYearTransform.call_order, ["lookup", "transform"] |
| 614 |
) |
| 615 |
TrackCallsYearTransform.call_order = [] |
| 616 |
# junk transform - tries transform only, then fails |
| 617 |
msg = ( |
| 618 |
"Unsupported lookup 'junk__more_junk' for IntegerField or join" |
| 619 |
" on the field not permitted." |
| 620 |
) |
| 621 |
with self.assertRaisesMessage(FieldError, msg): |
| 622 |
Author.objects.filter(birthdate__testyear__junk__more_junk=2012) |
| 623 |
self.assertEqual(TrackCallsYearTransform.call_order, ["transform"]) |
| 624 |
TrackCallsYearTransform.call_order = [] |
| 625 |
# Just getting the year (implied __exact) - lookup only |
| 626 |
Author.objects.filter(birthdate__testyear=2012) |
| 627 |
self.assertEqual(TrackCallsYearTransform.call_order, ["lookup"]) |
| 628 |
TrackCallsYearTransform.call_order = [] |
| 629 |
# Just getting the year (explicit __exact) - lookup only |
| 630 |
Author.objects.filter(birthdate__testyear__exact=2012) |
| 631 |
self.assertEqual(TrackCallsYearTransform.call_order, ["lookup"]) |
| 632 |
|
| 633 |
|
| 634 |
class CustomisedMethodsTests(SimpleTestCase): |
| 635 |
def test_overridden_get_lookup(self): |
| 636 |
q = CustomModel.objects.filter(field__lookupfunc_monkeys=3) |
| 637 |
self.assertIn("monkeys()", str(q.query)) |
| 638 |
|
| 639 |
def test_overridden_get_transform(self): |
| 640 |
q = CustomModel.objects.filter(field__transformfunc_banana=3) |
| 641 |
self.assertIn("banana()", str(q.query)) |
| 642 |
|
| 643 |
def test_overridden_get_lookup_chain(self): |
| 644 |
q = CustomModel.objects.filter( |
| 645 |
field__transformfunc_banana__lookupfunc_elephants=3 |
| 646 |
) |
| 647 |
self.assertIn("elephants()", str(q.query)) |
| 648 |
|
| 649 |
def test_overridden_get_transform_chain(self): |
| 650 |
q = CustomModel.objects.filter( |
| 651 |
field__transformfunc_banana__transformfunc_pear=3 |
| 652 |
) |
| 653 |
self.assertIn("pear()", str(q.query)) |
| 654 |
|
| 655 |
|
| 656 |
class SubqueryTransformTests(TestCase): |
| 657 |
def test_subquery_usage(self): |
| 658 |
with register_lookup(models.IntegerField, Div3Transform): |
| 659 |
Author.objects.create(name="a1", age=1) |
| 660 |
a2 = Author.objects.create(name="a2", age=2) |
| 661 |
Author.objects.create(name="a3", age=3) |
| 662 |
Author.objects.create(name="a4", age=4) |
| 663 |
qs = Author.objects.order_by("name").filter( |
| 664 |
id__in=Author.objects.filter(age__div3=2) |
| 665 |
) |
| 666 |
self.assertSequenceEqual(qs, [a2]) |
| 667 |
|
| 668 |
|
| 669 |
class RegisterLookupTests(SimpleTestCase): |
| 670 |
def test_class_lookup(self): |
| 671 |
author_name = Author._meta.get_field("name") |
| 672 |
with register_lookup(models.CharField, CustomStartsWith): |
| 673 |
self.assertEqual(author_name.get_lookup("sw"), CustomStartsWith) |
| 674 |
self.assertIsNone(author_name.get_lookup("sw")) |
| 675 |
|
| 676 |
def test_instance_lookup(self): |
| 677 |
author_name = Author._meta.get_field("name") |
| 678 |
author_alias = Author._meta.get_field("alias") |
| 679 |
with register_lookup(author_name, CustomStartsWith): |
| 680 |
self.assertEqual(author_name.instance_lookups, {"sw": CustomStartsWith}) |
| 681 |
self.assertEqual(author_name.get_lookup("sw"), CustomStartsWith) |
| 682 |
self.assertIsNone(author_alias.get_lookup("sw")) |
| 683 |
self.assertIsNone(author_name.get_lookup("sw")) |
| 684 |
self.assertEqual(author_name.instance_lookups, {}) |
| 685 |
self.assertIsNone(author_alias.get_lookup("sw")) |
| 686 |
|
| 687 |
def test_instance_lookup_override_class_lookups(self): |
| 688 |
author_name = Author._meta.get_field("name") |
| 689 |
author_alias = Author._meta.get_field("alias") |
| 690 |
with register_lookup(models.CharField, CustomStartsWith, lookup_name="st_end"): |
| 691 |
with register_lookup(author_alias, CustomEndsWith, lookup_name="st_end"): |
| 692 |
self.assertEqual(author_name.get_lookup("st_end"), CustomStartsWith) |
| 693 |
self.assertEqual(author_alias.get_lookup("st_end"), CustomEndsWith) |
| 694 |
self.assertEqual(author_name.get_lookup("st_end"), CustomStartsWith) |
| 695 |
self.assertEqual(author_alias.get_lookup("st_end"), CustomStartsWith) |
| 696 |
self.assertIsNone(author_name.get_lookup("st_end")) |
| 697 |
self.assertIsNone(author_alias.get_lookup("st_end")) |
| 698 |
|
| 699 |
def test_instance_lookup_override(self): |
| 700 |
author_name = Author._meta.get_field("name") |
| 701 |
with register_lookup(author_name, CustomStartsWith, lookup_name="st_end"): |
| 702 |
self.assertEqual(author_name.get_lookup("st_end"), CustomStartsWith) |
| 703 |
author_name.register_lookup(CustomEndsWith, lookup_name="st_end") |
| 704 |
self.assertEqual(author_name.get_lookup("st_end"), CustomEndsWith) |
| 705 |
self.assertIsNone(author_name.get_lookup("st_end")) |
| 706 |
|
| 707 |
def test_lookup_on_transform(self): |
| 708 |
transform = Div3Transform |
| 709 |
with register_lookup(Div3Transform, CustomStartsWith): |
| 710 |
with register_lookup(Div3Transform, CustomEndsWith): |
| 711 |
self.assertEqual( |
| 712 |
transform.get_lookups(), |
| 713 |
{"sw": CustomStartsWith, "ew": CustomEndsWith}, |
| 714 |
) |
| 715 |
self.assertEqual(transform.get_lookups(), {"sw": CustomStartsWith}) |
| 716 |
self.assertEqual(transform.get_lookups(), {}) |
| 717 |
|
| 718 |
def test_transform_on_field(self): |
| 719 |
author_name = Author._meta.get_field("name") |
| 720 |
author_alias = Author._meta.get_field("alias") |
| 721 |
with register_lookup(models.CharField, Div3Transform): |
| 722 |
self.assertEqual(author_alias.get_transform("div3"), Div3Transform) |
| 723 |
self.assertEqual(author_name.get_transform("div3"), Div3Transform) |
| 724 |
with register_lookup(author_alias, Div3Transform): |
| 725 |
self.assertEqual(author_alias.get_transform("div3"), Div3Transform) |
| 726 |
self.assertIsNone(author_name.get_transform("div3")) |
| 727 |
self.assertIsNone(author_alias.get_transform("div3")) |
| 728 |
self.assertIsNone(author_name.get_transform("div3")) |
| 729 |
|
| 730 |
def test_related_lookup(self): |
| 731 |
article_author = Article._meta.get_field("author") |
| 732 |
with register_lookup(models.Field, CustomStartsWith): |
| 733 |
self.assertIsNone(article_author.get_lookup("sw")) |
| 734 |
with register_lookup(models.ForeignKey, RelatedMoreThan): |
| 735 |
self.assertEqual(article_author.get_lookup("rmt"), RelatedMoreThan) |
| 736 |
|
| 737 |
def test_instance_related_lookup(self): |
| 738 |
article_author = Article._meta.get_field("author") |
| 739 |
with register_lookup(article_author, RelatedMoreThan): |
| 740 |
self.assertEqual(article_author.get_lookup("rmt"), RelatedMoreThan) |
| 741 |
self.assertIsNone(article_author.get_lookup("rmt")) |