| 1 |
from django.contrib.gis.db.models import Collect, Count, Extent, F, MakeLine, Q, Union |
| 2 |
from django.contrib.gis.db.models.functions import Centroid |
| 3 |
from django.contrib.gis.geos import GEOSGeometry, MultiPoint, Point |
| 4 |
from django.db import NotSupportedError, connection |
| 5 |
from django.test import TestCase, skipUnlessDBFeature |
| 6 |
from django.test.utils import override_settings |
| 7 |
from django.utils import timezone |
| 8 |
|
| 9 |
from .models import Article, Author, Book, City, DirectoryEntry, Event, Location, Parcel |
| 10 |
|
| 11 |
|
| 12 |
class RelatedGeoModelTest(TestCase): |
| 13 |
fixtures = ["initial"] |
| 14 |
|
| 15 |
def test02_select_related(self): |
| 16 |
"Testing `select_related` on geographic models (see #7126)." |
| 17 |
qs1 = City.objects.order_by("id") |
| 18 |
qs2 = City.objects.order_by("id").select_related() |
| 19 |
qs3 = City.objects.order_by("id").select_related("location") |
| 20 |
|
| 21 |
# Reference data for what's in the fixtures. |
| 22 |
cities = ( |
| 23 |
("Aurora", "TX", -97.516111, 33.058333), |
| 24 |
("Roswell", "NM", -104.528056, 33.387222), |
| 25 |
("Kecksburg", "PA", -79.460734, 40.18476), |
| 26 |
) |
| 27 |
|
| 28 |
for qs in (qs1, qs2, qs3): |
| 29 |
for ref, c in zip(cities, qs): |
| 30 |
nm, st, lon, lat = ref |
| 31 |
self.assertEqual(nm, c.name) |
| 32 |
self.assertEqual(st, c.state) |
| 33 |
self.assertAlmostEqual(lon, c.location.point.x, 6) |
| 34 |
self.assertAlmostEqual(lat, c.location.point.y, 6) |
| 35 |
|
| 36 |
@skipUnlessDBFeature("supports_extent_aggr") |
| 37 |
def test_related_extent_aggregate(self): |
| 38 |
"Testing the `Extent` aggregate on related geographic models." |
| 39 |
# This combines the Extent and Union aggregates into one query |
| 40 |
aggs = City.objects.aggregate(Extent("location__point")) |
| 41 |
|
| 42 |
# One for all locations, one that excludes New Mexico (Roswell). |
| 43 |
all_extent = (-104.528056, 29.763374, -79.460734, 40.18476) |
| 44 |
txpa_extent = (-97.516111, 29.763374, -79.460734, 40.18476) |
| 45 |
e1 = City.objects.aggregate(Extent("location__point"))[ |
| 46 |
"location__point__extent" |
| 47 |
] |
| 48 |
e2 = City.objects.exclude(state="NM").aggregate(Extent("location__point"))[ |
| 49 |
"location__point__extent" |
| 50 |
] |
| 51 |
e3 = aggs["location__point__extent"] |
| 52 |
|
| 53 |
# The tolerance value is to four decimal places because of differences |
| 54 |
# between the Oracle and PostGIS spatial backends on the extent calculation. |
| 55 |
tol = 4 |
| 56 |
for ref, e in [(all_extent, e1), (txpa_extent, e2), (all_extent, e3)]: |
| 57 |
for ref_val, e_val in zip(ref, e): |
| 58 |
self.assertAlmostEqual(ref_val, e_val, tol) |
| 59 |
|
| 60 |
@skipUnlessDBFeature("supports_extent_aggr") |
| 61 |
def test_related_extent_annotate(self): |
| 62 |
""" |
| 63 |
Test annotation with Extent GeoAggregate. |
| 64 |
""" |
| 65 |
cities = City.objects.annotate( |
| 66 |
points_extent=Extent("location__point") |
| 67 |
).order_by("name") |
| 68 |
tol = 4 |
| 69 |
self.assertAlmostEqual( |
| 70 |
cities[0].points_extent, (-97.516111, 33.058333, -97.516111, 33.058333), tol |
| 71 |
) |
| 72 |
|
| 73 |
@skipUnlessDBFeature("supports_union_aggr") |
| 74 |
def test_related_union_aggregate(self): |
| 75 |
"Testing the `Union` aggregate on related geographic models." |
| 76 |
# This combines the Extent and Union aggregates into one query |
| 77 |
aggs = City.objects.aggregate(Union("location__point")) |
| 78 |
|
| 79 |
# These are the points that are components of the aggregate geographic |
| 80 |
# union that is returned. Each point # corresponds to City PK. |
| 81 |
p1 = Point(-104.528056, 33.387222) |
| 82 |
p2 = Point(-97.516111, 33.058333) |
| 83 |
p3 = Point(-79.460734, 40.18476) |
| 84 |
p4 = Point(-96.801611, 32.782057) |
| 85 |
p5 = Point(-95.363151, 29.763374) |
| 86 |
|
| 87 |
# The second union aggregate is for a union |
| 88 |
# query that includes limiting information in the WHERE clause (in other |
| 89 |
# words a `.filter()` precedes the call to `.aggregate(Union()`). |
| 90 |
ref_u1 = MultiPoint(p1, p2, p4, p5, p3, srid=4326) |
| 91 |
ref_u2 = MultiPoint(p2, p3, srid=4326) |
| 92 |
|
| 93 |
u1 = City.objects.aggregate(Union("location__point"))["location__point__union"] |
| 94 |
u2 = City.objects.exclude( |
| 95 |
name__in=("Roswell", "Houston", "Dallas", "Fort Worth"), |
| 96 |
).aggregate(Union("location__point"))["location__point__union"] |
| 97 |
u3 = aggs["location__point__union"] |
| 98 |
self.assertEqual(type(u1), MultiPoint) |
| 99 |
self.assertEqual(type(u3), MultiPoint) |
| 100 |
|
| 101 |
# Ordering of points in the result of the union is not defined and |
| 102 |
# implementation-dependent (DB backend, GEOS version). |
| 103 |
tests = [ |
| 104 |
(u1, ref_u1), |
| 105 |
(u2, ref_u2), |
| 106 |
(u3, ref_u1), |
| 107 |
] |
| 108 |
for union, ref in tests: |
| 109 |
for point, ref_point in zip(sorted(union), sorted(ref), strict=True): |
| 110 |
self.assertIs(point.equals_exact(ref_point, tolerance=6), True) |
| 111 |
|
| 112 |
def test05_select_related_fk_to_subclass(self): |
| 113 |
""" |
| 114 |
select_related on a query over a model with an FK to a model subclass. |
| 115 |
""" |
| 116 |
# Regression test for #9752. |
| 117 |
list(DirectoryEntry.objects.select_related()) |
| 118 |
|
| 119 |
def test06_f_expressions(self): |
| 120 |
"Testing F() expressions on GeometryFields." |
| 121 |
# Constructing a dummy parcel border and getting the City instance for |
| 122 |
# assigning the FK. |
| 123 |
b1 = GEOSGeometry( |
| 124 |
"POLYGON((-97.501205 33.052520,-97.501205 33.052576," |
| 125 |
"-97.501150 33.052576,-97.501150 33.052520,-97.501205 33.052520))", |
| 126 |
srid=4326, |
| 127 |
) |
| 128 |
pcity = City.objects.get(name="Aurora") |
| 129 |
|
| 130 |
# First parcel has incorrect center point that is equal to the City; |
| 131 |
# it also has a second border that is different from the first as a |
| 132 |
# 100ft buffer around the City. |
| 133 |
c1 = pcity.location.point |
| 134 |
c2 = c1.transform(2276, clone=True) |
| 135 |
b2 = c2.buffer(100) |
| 136 |
Parcel.objects.create( |
| 137 |
name="P1", city=pcity, center1=c1, center2=c2, border1=b1, border2=b2 |
| 138 |
) |
| 139 |
|
| 140 |
# Now creating a second Parcel where the borders are the same, just |
| 141 |
# in different coordinate systems. The center points are also the |
| 142 |
# same (but in different coordinate systems), and this time they |
| 143 |
# actually correspond to the centroid of the border. |
| 144 |
c1 = b1.centroid |
| 145 |
c2 = c1.transform(2276, clone=True) |
| 146 |
b2 = ( |
| 147 |
b1 |
| 148 |
if connection.features.supports_transform |
| 149 |
else b1.transform(2276, clone=True) |
| 150 |
) |
| 151 |
Parcel.objects.create( |
| 152 |
name="P2", city=pcity, center1=c1, center2=c2, border1=b1, border2=b2 |
| 153 |
) |
| 154 |
|
| 155 |
# Should return the second Parcel, which has the center within the |
| 156 |
# border. |
| 157 |
qs = Parcel.objects.filter(center1__within=F("border1")) |
| 158 |
self.assertEqual(1, len(qs)) |
| 159 |
self.assertEqual("P2", qs[0].name) |
| 160 |
|
| 161 |
# This time center2 is in a different coordinate system and needs to be |
| 162 |
# wrapped in transformation SQL. |
| 163 |
qs = Parcel.objects.filter(center2__within=F("border1")) |
| 164 |
if connection.features.supports_transform: |
| 165 |
self.assertEqual("P2", qs.get().name) |
| 166 |
else: |
| 167 |
msg = "This backend doesn't support the Transform function." |
| 168 |
with self.assertRaisesMessage(NotSupportedError, msg): |
| 169 |
list(qs) |
| 170 |
|
| 171 |
# Should return the first Parcel, which has the center point equal |
| 172 |
# to the point in the City ForeignKey. |
| 173 |
qs = Parcel.objects.filter(center1=F("city__location__point")) |
| 174 |
self.assertEqual(1, len(qs)) |
| 175 |
self.assertEqual("P1", qs[0].name) |
| 176 |
|
| 177 |
# This time the city column should be wrapped in transformation SQL. |
| 178 |
qs = Parcel.objects.filter(border2__contains=F("city__location__point")) |
| 179 |
if connection.features.supports_transform: |
| 180 |
self.assertEqual("P1", qs.get().name) |
| 181 |
else: |
| 182 |
msg = "This backend doesn't support the Transform function." |
| 183 |
with self.assertRaisesMessage(NotSupportedError, msg): |
| 184 |
list(qs) |
| 185 |
|
| 186 |
def test07_values(self): |
| 187 |
"Testing values() and values_list()." |
| 188 |
gqs = Location.objects.all() |
| 189 |
gvqs = Location.objects.values() |
| 190 |
gvlqs = Location.objects.values_list() |
| 191 |
|
| 192 |
# Incrementing through each of the models, dictionaries, and tuples |
| 193 |
# returned by each QuerySet. |
| 194 |
for m, d, t in zip(gqs, gvqs, gvlqs): |
| 195 |
# The values should be Geometry objects and not raw strings returned |
| 196 |
# by the spatial database. |
| 197 |
self.assertIsInstance(d["point"], GEOSGeometry) |
| 198 |
self.assertIsInstance(t[1], GEOSGeometry) |
| 199 |
self.assertEqual(m.point, d["point"]) |
| 200 |
self.assertEqual(m.point, t[1]) |
| 201 |
|
| 202 |
@override_settings(USE_TZ=True) |
| 203 |
def test_07b_values(self): |
| 204 |
"Testing values() and values_list() with aware datetime. See #21565." |
| 205 |
Event.objects.create(name="foo", when=timezone.now()) |
| 206 |
list(Event.objects.values_list("when")) |
| 207 |
|
| 208 |
def test08_defer_only(self): |
| 209 |
"Testing defer() and only() on Geographic models." |
| 210 |
qs = Location.objects.all().order_by("pk") |
| 211 |
def_qs = Location.objects.defer("point").order_by("pk") |
| 212 |
for loc, def_loc in zip(qs, def_qs): |
| 213 |
self.assertEqual(loc.point, def_loc.point) |
| 214 |
|
| 215 |
def test09_pk_relations(self): |
| 216 |
"Ensuring correct primary key column is selected across relations. See #10757." |
| 217 |
# The expected ID values -- notice the last two location IDs |
| 218 |
# are out of order. Dallas and Houston have location IDs that differ |
| 219 |
# from their PKs -- this is done to ensure that the related location |
| 220 |
# ID column is selected instead of ID column for the city. |
| 221 |
city_ids = (1, 2, 3, 4, 5) |
| 222 |
loc_ids = (1, 2, 3, 5, 4) |
| 223 |
ids_qs = City.objects.order_by("id").values("id", "location__id") |
| 224 |
for val_dict, c_id, l_id in zip(ids_qs, city_ids, loc_ids): |
| 225 |
self.assertEqual(val_dict["id"], c_id) |
| 226 |
self.assertEqual(val_dict["location__id"], l_id) |
| 227 |
|
| 228 |
def test10_combine(self): |
| 229 |
"Testing the combination of two QuerySets (#10807)." |
| 230 |
buf1 = City.objects.get(name="Aurora").location.point.buffer(0.1) |
| 231 |
buf2 = City.objects.get(name="Kecksburg").location.point.buffer(0.1) |
| 232 |
qs1 = City.objects.filter(location__point__within=buf1) |
| 233 |
qs2 = City.objects.filter(location__point__within=buf2) |
| 234 |
combined = qs1 | qs2 |
| 235 |
names = [c.name for c in combined] |
| 236 |
self.assertEqual(2, len(names)) |
| 237 |
self.assertIn("Aurora", names) |
| 238 |
self.assertIn("Kecksburg", names) |
| 239 |
|
| 240 |
@skipUnlessDBFeature("allows_group_by_lob") |
| 241 |
def test12a_count(self): |
| 242 |
"Testing `Count` aggregate on geo-fields." |
| 243 |
# The City, 'Fort Worth' uses the same location as Dallas. |
| 244 |
dallas = City.objects.get(name="Dallas") |
| 245 |
|
| 246 |
# Count annotation should be 2 for the Dallas location now. |
| 247 |
loc = Location.objects.annotate(num_cities=Count("city")).get( |
| 248 |
id=dallas.location.id |
| 249 |
) |
| 250 |
self.assertEqual(2, loc.num_cities) |
| 251 |
|
| 252 |
def test12b_count(self): |
| 253 |
"Testing `Count` aggregate on non geo-fields." |
| 254 |
# Should only be one author (Trevor Paglen) returned by this query, and |
| 255 |
# the annotation should have 3 for the number of books, see #11087. |
| 256 |
# Also testing with a values(), see #11489. |
| 257 |
qs = Author.objects.annotate(num_books=Count("books")).filter(num_books__gt=1) |
| 258 |
vqs = ( |
| 259 |
Author.objects.values("name") |
| 260 |
.annotate(num_books=Count("books")) |
| 261 |
.filter(num_books__gt=1) |
| 262 |
) |
| 263 |
self.assertEqual(1, len(qs)) |
| 264 |
self.assertEqual(3, qs[0].num_books) |
| 265 |
self.assertEqual(1, len(vqs)) |
| 266 |
self.assertEqual(3, vqs[0]["num_books"]) |
| 267 |
|
| 268 |
@skipUnlessDBFeature("allows_group_by_lob") |
| 269 |
def test13c_count(self): |
| 270 |
"Testing `Count` aggregate with `.values()`. See #15305." |
| 271 |
qs = ( |
| 272 |
Location.objects.filter(id=5) |
| 273 |
.annotate(num_cities=Count("city")) |
| 274 |
.values("id", "point", "num_cities") |
| 275 |
) |
| 276 |
self.assertEqual(1, len(qs)) |
| 277 |
self.assertEqual(2, qs[0]["num_cities"]) |
| 278 |
self.assertIsInstance(qs[0]["point"], GEOSGeometry) |
| 279 |
|
| 280 |
def test13_select_related_null_fk(self): |
| 281 |
"Testing `select_related` on a nullable ForeignKey." |
| 282 |
Book.objects.create(title="Without Author") |
| 283 |
b = Book.objects.select_related("author").get(title="Without Author") |
| 284 |
# Should be `None`, and not a 'dummy' model. |
| 285 |
self.assertIsNone(b.author) |
| 286 |
|
| 287 |
@skipUnlessDBFeature("supports_collect_aggr") |
| 288 |
def test_collect(self): |
| 289 |
""" |
| 290 |
Testing the `Collect` aggregate. |
| 291 |
""" |
| 292 |
# Reference query: |
| 293 |
# SELECT AsText(ST_Collect("relatedapp_location"."point")) |
| 294 |
# FROM "relatedapp_city" |
| 295 |
# LEFT OUTER JOIN |
| 296 |
# "relatedapp_location" ON ( |
| 297 |
# "relatedapp_city"."location_id" = "relatedapp_location"."id" |
| 298 |
# ) |
| 299 |
# WHERE "relatedapp_city"."state" = 'TX'; |
| 300 |
ref_geom = GEOSGeometry( |
| 301 |
"MULTIPOINT(-97.516111 33.058333,-96.801611 32.782057," |
| 302 |
"-95.363151 29.763374,-96.801611 32.782057)" |
| 303 |
) |
| 304 |
|
| 305 |
coll = City.objects.filter(state="TX").aggregate(Collect("location__point"))[ |
| 306 |
"location__point__collect" |
| 307 |
] |
| 308 |
# Even though Dallas and Ft. Worth share same point, Collect doesn't |
| 309 |
# consolidate -- that's why 4 points in MultiPoint. |
| 310 |
self.assertEqual(4, len(coll)) |
| 311 |
self.assertTrue(ref_geom.equals(coll)) |
| 312 |
|
| 313 |
@skipUnlessDBFeature("supports_collect_aggr") |
| 314 |
def test_collect_filter(self): |
| 315 |
qs = City.objects.annotate( |
| 316 |
parcel_center=Collect( |
| 317 |
"parcel__center1", |
| 318 |
filter=~Q(parcel__name__icontains="ignore"), |
| 319 |
), |
| 320 |
parcel_center_nonexistent=Collect( |
| 321 |
"parcel__center1", |
| 322 |
filter=Q(parcel__name__icontains="nonexistent"), |
| 323 |
), |
| 324 |
parcel_center_single=Collect( |
| 325 |
"parcel__center1", |
| 326 |
filter=Q(parcel__name__contains="Alpha"), |
| 327 |
), |
| 328 |
) |
| 329 |
city = qs.get(name="Aurora") |
| 330 |
self.assertEqual( |
| 331 |
city.parcel_center.wkt, |
| 332 |
GEOSGeometry("MULTIPOINT (1.7128 -2.006, 4.7128 5.006)"), |
| 333 |
) |
| 334 |
self.assertIsNone(city.parcel_center_nonexistent) |
| 335 |
self.assertIn( |
| 336 |
city.parcel_center_single.wkt, |
| 337 |
[ |
| 338 |
GEOSGeometry("MULTIPOINT (1.7128 -2.006)"), |
| 339 |
GEOSGeometry("POINT (1.7128 -2.006)"), # SpatiaLite collapse to POINT. |
| 340 |
], |
| 341 |
) |
| 342 |
|
| 343 |
@skipUnlessDBFeature("has_Centroid_function", "supports_collect_aggr") |
| 344 |
def test_centroid_collect_filter(self): |
| 345 |
qs = City.objects.annotate( |
| 346 |
parcel_centroid=Centroid( |
| 347 |
Collect( |
| 348 |
"parcel__center1", |
| 349 |
filter=~Q(parcel__name__icontains="ignore"), |
| 350 |
) |
| 351 |
) |
| 352 |
) |
| 353 |
city = qs.get(name="Aurora") |
| 354 |
self.assertIsInstance(city.parcel_centroid, Point) |
| 355 |
self.assertAlmostEqual(city.parcel_centroid[0], 3.2128, 4) |
| 356 |
self.assertAlmostEqual(city.parcel_centroid[1], 1.5, 4) |
| 357 |
|
| 358 |
@skipUnlessDBFeature("supports_make_line_aggr") |
| 359 |
def test_make_line_filter(self): |
| 360 |
qs = City.objects.annotate( |
| 361 |
parcel_line=MakeLine( |
| 362 |
"parcel__center1", |
| 363 |
filter=~Q(parcel__name__icontains="ignore"), |
| 364 |
), |
| 365 |
parcel_line_nonexistent=MakeLine( |
| 366 |
"parcel__center1", |
| 367 |
filter=Q(parcel__name__icontains="nonexistent"), |
| 368 |
), |
| 369 |
) |
| 370 |
city = qs.get(name="Aurora") |
| 371 |
self.assertIn( |
| 372 |
city.parcel_line.wkt, |
| 373 |
# The default ordering is flaky, so check both. |
| 374 |
[ |
| 375 |
"LINESTRING (1.7128 -2.006, 4.7128 5.006)", |
| 376 |
"LINESTRING (4.7128 5.006, 1.7128 -2.006)", |
| 377 |
], |
| 378 |
) |
| 379 |
self.assertIsNone(city.parcel_line_nonexistent) |
| 380 |
|
| 381 |
@skipUnlessDBFeature("supports_extent_aggr") |
| 382 |
def test_extent_filter(self): |
| 383 |
qs = City.objects.annotate( |
| 384 |
parcel_border=Extent( |
| 385 |
"parcel__border1", |
| 386 |
filter=~Q(parcel__name__icontains="ignore"), |
| 387 |
), |
| 388 |
parcel_border_nonexistent=Extent( |
| 389 |
"parcel__border1", |
| 390 |
filter=Q(parcel__name__icontains="nonexistent"), |
| 391 |
), |
| 392 |
parcel_border_no_filter=Extent("parcel__border1"), |
| 393 |
) |
| 394 |
city = qs.get(name="Aurora") |
| 395 |
self.assertEqual(city.parcel_border, (0.0, 0.0, 22.0, 22.0)) |
| 396 |
self.assertIsNone(city.parcel_border_nonexistent) |
| 397 |
self.assertEqual(city.parcel_border_no_filter, (0.0, 0.0, 32.0, 32.0)) |
| 398 |
|
| 399 |
@skipUnlessDBFeature("supports_union_aggr") |
| 400 |
def test_union_filter(self): |
| 401 |
qs = City.objects.annotate( |
| 402 |
parcel_point_union=Union( |
| 403 |
"parcel__center2", |
| 404 |
filter=~Q(parcel__name__icontains="ignore"), |
| 405 |
), |
| 406 |
parcel_point_nonexistent=Union( |
| 407 |
"parcel__center2", |
| 408 |
filter=Q(parcel__name__icontains="nonexistent"), |
| 409 |
), |
| 410 |
parcel_point_union_single=Union( |
| 411 |
"parcel__center2", |
| 412 |
filter=Q(parcel__name__contains="Alpha"), |
| 413 |
), |
| 414 |
) |
| 415 |
city = qs.get(name="Aurora") |
| 416 |
self.assertIn( |
| 417 |
city.parcel_point_union.wkt, |
| 418 |
[ |
| 419 |
GEOSGeometry("MULTIPOINT (12.75 10.05, 3.7128 -5.006)"), |
| 420 |
GEOSGeometry("MULTIPOINT (3.7128 -5.006, 12.75 10.05)"), |
| 421 |
], |
| 422 |
) |
| 423 |
self.assertIsNone(city.parcel_point_nonexistent) |
| 424 |
self.assertEqual(city.parcel_point_union_single.wkt, "POINT (3.7128 -5.006)") |
| 425 |
|
| 426 |
def test15_invalid_select_related(self): |
| 427 |
""" |
| 428 |
select_related on the related name manager of a unique FK. |
| 429 |
""" |
| 430 |
qs = Article.objects.select_related("author__article") |
| 431 |
# This triggers TypeError when `get_default_columns` has no `local_only` |
| 432 |
# keyword. The TypeError is swallowed if QuerySet is actually |
| 433 |
# evaluated as list generation swallows TypeError in CPython. |
| 434 |
str(qs.query) |
| 435 |
|
| 436 |
def test16_annotated_date_queryset(self): |
| 437 |
"Ensure annotated date querysets work if spatial backend is used. See #14648." |
| 438 |
birth_years = [ |
| 439 |
dt.year |
| 440 |
for dt in list( |
| 441 |
Author.objects.annotate(num_books=Count("books")).dates("dob", "year") |
| 442 |
) |
| 443 |
] |
| 444 |
birth_years.sort() |
| 445 |
self.assertEqual([1950, 1974], birth_years) |
| 446 |
|
| 447 |
# TODO: Related tests for KML, GML, and distance lookups. |