tests.py 18 KB

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