tests.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  1. import unittest
  2. from django.contrib.gis.db.models.functions import (
  3. Area, Distance, Length, Perimeter, Transform, Union,
  4. )
  5. from django.contrib.gis.geos import GEOSGeometry, LineString, Point
  6. from django.contrib.gis.measure import D # alias for Distance
  7. from django.db import connection
  8. from django.db.models import F, Q
  9. from django.test import TestCase, skipIfDBFeature, skipUnlessDBFeature
  10. from ..utils import mysql, no_oracle, oracle, postgis, spatialite
  11. from .models import (
  12. AustraliaCity, CensusZipcode, Interstate, SouthTexasCity, SouthTexasCityFt,
  13. SouthTexasInterstate, SouthTexasZipcode,
  14. )
  15. class DistanceTest(TestCase):
  16. fixtures = ['initial']
  17. def setUp(self):
  18. # A point we are testing distances with -- using a WGS84
  19. # coordinate that'll be implicitly transformed to that to
  20. # the coordinate system of the field, EPSG:32140 (Texas South Central
  21. # w/units in meters)
  22. self.stx_pnt = GEOSGeometry('POINT (-95.370401017314293 29.704867409475465)', 4326)
  23. # Another one for Australia
  24. self.au_pnt = GEOSGeometry('POINT (150.791 -34.4919)', 4326)
  25. def get_names(self, qs):
  26. cities = [c.name for c in qs]
  27. cities.sort()
  28. return cities
  29. def test_init(self):
  30. """
  31. Test initialization of distance models.
  32. """
  33. self.assertEqual(9, SouthTexasCity.objects.count())
  34. self.assertEqual(9, SouthTexasCityFt.objects.count())
  35. self.assertEqual(11, AustraliaCity.objects.count())
  36. self.assertEqual(4, SouthTexasZipcode.objects.count())
  37. self.assertEqual(4, CensusZipcode.objects.count())
  38. self.assertEqual(1, Interstate.objects.count())
  39. self.assertEqual(1, SouthTexasInterstate.objects.count())
  40. @skipUnlessDBFeature("supports_dwithin_lookup")
  41. def test_dwithin(self):
  42. """
  43. Test the `dwithin` lookup type.
  44. """
  45. # Distances -- all should be equal (except for the
  46. # degree/meter pair in au_cities, that's somewhat
  47. # approximate).
  48. tx_dists = [(7000, 22965.83), D(km=7), D(mi=4.349)]
  49. au_dists = [(0.5, 32000), D(km=32), D(mi=19.884)]
  50. # Expected cities for Australia and Texas.
  51. tx_cities = ['Downtown Houston', 'Southside Place']
  52. au_cities = ['Mittagong', 'Shellharbour', 'Thirroul', 'Wollongong']
  53. # Performing distance queries on two projected coordinate systems one
  54. # with units in meters and the other in units of U.S. survey feet.
  55. for dist in tx_dists:
  56. if isinstance(dist, tuple):
  57. dist1, dist2 = dist
  58. else:
  59. dist1 = dist2 = dist
  60. qs1 = SouthTexasCity.objects.filter(point__dwithin=(self.stx_pnt, dist1))
  61. qs2 = SouthTexasCityFt.objects.filter(point__dwithin=(self.stx_pnt, dist2))
  62. for qs in qs1, qs2:
  63. with self.subTest(dist=dist, qs=qs):
  64. self.assertEqual(tx_cities, self.get_names(qs))
  65. # Now performing the `dwithin` queries on a geodetic coordinate system.
  66. for dist in au_dists:
  67. with self.subTest(dist=dist):
  68. if isinstance(dist, D) and not oracle:
  69. type_error = True
  70. else:
  71. type_error = False
  72. if isinstance(dist, tuple):
  73. if oracle or spatialite:
  74. # Result in meters
  75. dist = dist[1]
  76. else:
  77. # Result in units of the field
  78. dist = dist[0]
  79. # Creating the query set.
  80. qs = AustraliaCity.objects.order_by('name')
  81. if type_error:
  82. # A ValueError should be raised on PostGIS when trying to
  83. # pass Distance objects into a DWithin query using a
  84. # geodetic field.
  85. with self.assertRaises(ValueError):
  86. AustraliaCity.objects.filter(point__dwithin=(self.au_pnt, dist)).count()
  87. else:
  88. self.assertEqual(au_cities, self.get_names(qs.filter(point__dwithin=(self.au_pnt, dist))))
  89. @skipUnlessDBFeature("supports_distances_lookups")
  90. def test_distance_lookups(self):
  91. """
  92. Test the `distance_lt`, `distance_gt`, `distance_lte`, and `distance_gte` lookup types.
  93. """
  94. # Retrieving the cities within a 20km 'donut' w/a 7km radius 'hole'
  95. # (thus, Houston and Southside place will be excluded as tested in
  96. # the `test02_dwithin` above).
  97. for model in [SouthTexasCity, SouthTexasCityFt]:
  98. stx_pnt = self.stx_pnt.transform(model._meta.get_field('point').srid, clone=True)
  99. qs = model.objects.filter(point__distance_gte=(stx_pnt, D(km=7))).filter(
  100. point__distance_lte=(stx_pnt, D(km=20)),
  101. )
  102. cities = self.get_names(qs)
  103. self.assertEqual(cities, ['Bellaire', 'Pearland', 'West University Place'])
  104. # Doing a distance query using Polygons instead of a Point.
  105. z = SouthTexasZipcode.objects.get(name='77005')
  106. qs = SouthTexasZipcode.objects.exclude(name='77005').filter(poly__distance_lte=(z.poly, D(m=275)))
  107. self.assertEqual(['77025', '77401'], self.get_names(qs))
  108. # If we add a little more distance 77002 should be included.
  109. qs = SouthTexasZipcode.objects.exclude(name='77005').filter(poly__distance_lte=(z.poly, D(m=300)))
  110. self.assertEqual(['77002', '77025', '77401'], self.get_names(qs))
  111. @skipUnlessDBFeature("supports_distances_lookups", "supports_distance_geodetic")
  112. def test_geodetic_distance_lookups(self):
  113. """
  114. Test distance lookups on geodetic coordinate systems.
  115. """
  116. # Line is from Canberra to Sydney. Query is for all other cities within
  117. # a 100km of that line (which should exclude only Hobart & Adelaide).
  118. line = GEOSGeometry('LINESTRING(144.9630 -37.8143,151.2607 -33.8870)', 4326)
  119. dist_qs = AustraliaCity.objects.filter(point__distance_lte=(line, D(km=100)))
  120. expected_cities = [
  121. 'Batemans Bay', 'Canberra', 'Hillsdale',
  122. 'Melbourne', 'Mittagong', 'Shellharbour',
  123. 'Sydney', 'Thirroul', 'Wollongong',
  124. ]
  125. if spatialite:
  126. # SpatiaLite is less accurate and returns 102.8km for Batemans Bay.
  127. expected_cities.pop(0)
  128. self.assertEqual(expected_cities, self.get_names(dist_qs))
  129. msg = "2, 3, or 4-element tuple required for 'distance_lte' lookup."
  130. with self.assertRaisesMessage(ValueError, msg): # Too many params.
  131. len(AustraliaCity.objects.filter(point__distance_lte=('POINT(5 23)', D(km=100), 'spheroid', '4', None)))
  132. with self.assertRaisesMessage(ValueError, msg): # Too few params.
  133. len(AustraliaCity.objects.filter(point__distance_lte=('POINT(5 23)',)))
  134. msg = "For 4-element tuples the last argument must be the 'spheroid' directive."
  135. with self.assertRaisesMessage(ValueError, msg):
  136. len(AustraliaCity.objects.filter(point__distance_lte=('POINT(5 23)', D(km=100), 'spheroid', '4')))
  137. # Getting all cities w/in 550 miles of Hobart.
  138. hobart = AustraliaCity.objects.get(name='Hobart')
  139. qs = AustraliaCity.objects.exclude(name='Hobart').filter(point__distance_lte=(hobart.point, D(mi=550)))
  140. cities = self.get_names(qs)
  141. self.assertEqual(cities, ['Batemans Bay', 'Canberra', 'Melbourne'])
  142. # Cities that are either really close or really far from Wollongong --
  143. # and using different units of distance.
  144. wollongong = AustraliaCity.objects.get(name='Wollongong')
  145. d1, d2 = D(yd=19500), D(nm=400) # Yards (~17km) & Nautical miles.
  146. # Normal geodetic distance lookup (uses `distance_sphere` on PostGIS.
  147. gq1 = Q(point__distance_lte=(wollongong.point, d1))
  148. gq2 = Q(point__distance_gte=(wollongong.point, d2))
  149. qs1 = AustraliaCity.objects.exclude(name='Wollongong').filter(gq1 | gq2)
  150. # Geodetic distance lookup but telling GeoDjango to use `distance_spheroid`
  151. # instead (we should get the same results b/c accuracy variance won't matter
  152. # in this test case).
  153. querysets = [qs1]
  154. if connection.features.has_DistanceSpheroid_function:
  155. gq3 = Q(point__distance_lte=(wollongong.point, d1, 'spheroid'))
  156. gq4 = Q(point__distance_gte=(wollongong.point, d2, 'spheroid'))
  157. qs2 = AustraliaCity.objects.exclude(name='Wollongong').filter(gq3 | gq4)
  158. querysets.append(qs2)
  159. for qs in querysets:
  160. cities = self.get_names(qs)
  161. self.assertEqual(cities, ['Adelaide', 'Hobart', 'Shellharbour', 'Thirroul'])
  162. @skipUnlessDBFeature("supports_distances_lookups")
  163. def test_distance_lookups_with_expression_rhs(self):
  164. stx_pnt = self.stx_pnt.transform(SouthTexasCity._meta.get_field('point').srid, clone=True)
  165. qs = SouthTexasCity.objects.filter(
  166. point__distance_lte=(stx_pnt, F('radius')),
  167. ).order_by('name')
  168. self.assertEqual(
  169. self.get_names(qs),
  170. ['Bellaire', 'Downtown Houston', 'Southside Place', 'West University Place']
  171. )
  172. # With a combined expression
  173. qs = SouthTexasCity.objects.filter(
  174. point__distance_lte=(stx_pnt, F('radius') * 2),
  175. ).order_by('name')
  176. self.assertEqual(len(qs), 5)
  177. self.assertIn('Pearland', self.get_names(qs))
  178. # With spheroid param
  179. if connection.features.supports_distance_geodetic:
  180. hobart = AustraliaCity.objects.get(name='Hobart')
  181. qs = AustraliaCity.objects.filter(
  182. point__distance_lte=(hobart.point, F('radius') * 70, 'spheroid'),
  183. ).order_by('name')
  184. self.assertEqual(self.get_names(qs), ['Canberra', 'Hobart', 'Melbourne'])
  185. # With a complex geometry expression
  186. self.assertFalse(SouthTexasCity.objects.filter(point__distance_gt=(Union('point', 'point'), 0)))
  187. self.assertEqual(
  188. SouthTexasCity.objects.filter(point__distance_lte=(Union('point', 'point'), 0)).count(),
  189. SouthTexasCity.objects.count(),
  190. )
  191. @unittest.skipUnless(mysql, 'This is a MySQL-specific test')
  192. def test_mysql_geodetic_distance_error(self):
  193. msg = 'Only numeric values of degree units are allowed on geodetic distance queries.'
  194. with self.assertRaisesMessage(ValueError, msg):
  195. AustraliaCity.objects.filter(point__distance_lte=(Point(0, 0), D(m=100))).exists()
  196. '''
  197. =============================
  198. Distance functions on PostGIS
  199. =============================
  200. | Projected Geometry | Lon/lat Geometry | Geography (4326)
  201. ST_Distance(geom1, geom2) | OK (meters) | :-( (degrees) | OK (meters)
  202. ST_Distance(geom1, geom2, use_spheroid=False) | N/A | N/A | OK (meters), less accurate, quick
  203. Distance_Sphere(geom1, geom2) | N/A | OK (meters) | N/A
  204. Distance_Spheroid(geom1, geom2, spheroid) | N/A | OK (meters) | N/A
  205. ST_Perimeter(geom1) | OK | :-( (degrees) | OK
  206. ================================
  207. Distance functions on SpatiaLite
  208. ================================
  209. | Projected Geometry | Lon/lat Geometry
  210. ST_Distance(geom1, geom2) | OK (meters) | N/A
  211. ST_Distance(geom1, geom2, use_ellipsoid=True) | N/A | OK (meters)
  212. ST_Distance(geom1, geom2, use_ellipsoid=False) | N/A | OK (meters), less accurate, quick
  213. Perimeter(geom1) | OK | :-( (degrees)
  214. ''' # NOQA
  215. class DistanceFunctionsTests(TestCase):
  216. fixtures = ['initial']
  217. @skipUnlessDBFeature("has_Area_function")
  218. def test_area(self):
  219. # Reference queries:
  220. # SELECT ST_Area(poly) FROM distapp_southtexaszipcode;
  221. area_sq_m = [5437908.90234375, 10183031.4389648, 11254471.0073242, 9881708.91772461]
  222. # Tolerance has to be lower for Oracle
  223. tol = 2
  224. for i, z in enumerate(SouthTexasZipcode.objects.annotate(area=Area('poly')).order_by('name')):
  225. self.assertAlmostEqual(area_sq_m[i], z.area.sq_m, tol)
  226. @skipUnlessDBFeature("has_Distance_function")
  227. def test_distance_simple(self):
  228. """
  229. Test a simple distance query, with projected coordinates and without
  230. transformation.
  231. """
  232. lagrange = GEOSGeometry('POINT(805066.295722839 4231496.29461335)', 32140)
  233. houston = SouthTexasCity.objects.annotate(dist=Distance('point', lagrange)).order_by('id').first()
  234. tol = 2 if oracle else 5
  235. self.assertAlmostEqual(
  236. houston.dist.m,
  237. 147075.069813,
  238. tol
  239. )
  240. @skipUnlessDBFeature("has_Distance_function", "has_Transform_function")
  241. def test_distance_projected(self):
  242. """
  243. Test the `Distance` function on projected coordinate systems.
  244. """
  245. # The point for La Grange, TX
  246. lagrange = GEOSGeometry('POINT(-96.876369 29.905320)', 4326)
  247. # Reference distances in feet and in meters. Got these values from
  248. # using the provided raw SQL statements.
  249. # SELECT ST_Distance(point, ST_Transform(ST_GeomFromText('POINT(-96.876369 29.905320)', 4326), 32140))
  250. # FROM distapp_southtexascity;
  251. m_distances = [147075.069813, 139630.198056, 140888.552826,
  252. 138809.684197, 158309.246259, 212183.594374,
  253. 70870.188967, 165337.758878, 139196.085105]
  254. # SELECT ST_Distance(point, ST_Transform(ST_GeomFromText('POINT(-96.876369 29.905320)', 4326), 2278))
  255. # FROM distapp_southtexascityft;
  256. ft_distances = [482528.79154625, 458103.408123001, 462231.860397575,
  257. 455411.438904354, 519386.252102563, 696139.009211594,
  258. 232513.278304279, 542445.630586414, 456679.155883207]
  259. # Testing using different variations of parameters and using models
  260. # with different projected coordinate systems.
  261. dist1 = SouthTexasCity.objects.annotate(distance=Distance('point', lagrange)).order_by('id')
  262. dist2 = SouthTexasCityFt.objects.annotate(distance=Distance('point', lagrange)).order_by('id')
  263. dist_qs = [dist1, dist2]
  264. # Original query done on PostGIS, have to adjust AlmostEqual tolerance
  265. # for Oracle.
  266. tol = 2 if oracle else 5
  267. # Ensuring expected distances are returned for each distance queryset.
  268. for qs in dist_qs:
  269. for i, c in enumerate(qs):
  270. with self.subTest(c=c):
  271. self.assertAlmostEqual(m_distances[i], c.distance.m, tol)
  272. self.assertAlmostEqual(ft_distances[i], c.distance.survey_ft, tol)
  273. @skipUnlessDBFeature("has_Distance_function", "supports_distance_geodetic")
  274. def test_distance_geodetic(self):
  275. """
  276. Test the `Distance` function on geodetic coordinate systems.
  277. """
  278. # Testing geodetic distance calculation with a non-point geometry
  279. # (a LineString of Wollongong and Shellharbour coords).
  280. ls = LineString(((150.902, -34.4245), (150.87, -34.5789)), srid=4326)
  281. # Reference query:
  282. # SELECT ST_distance_sphere(point, ST_GeomFromText('LINESTRING(150.9020 -34.4245,150.8700 -34.5789)', 4326))
  283. # FROM distapp_australiacity ORDER BY name;
  284. distances = [1120954.92533513, 140575.720018241, 640396.662906304,
  285. 60580.9693849269, 972807.955955075, 568451.8357838,
  286. 40435.4335201384, 0, 68272.3896586844, 12375.0643697706, 0]
  287. qs = AustraliaCity.objects.annotate(distance=Distance('point', ls)).order_by('name')
  288. for city, distance in zip(qs, distances):
  289. with self.subTest(city=city, distance=distance):
  290. # Testing equivalence to within a meter (kilometer on SpatiaLite).
  291. tol = -3 if spatialite else 0
  292. self.assertAlmostEqual(distance, city.distance.m, tol)
  293. @skipUnlessDBFeature("has_Distance_function", "supports_distance_geodetic")
  294. def test_distance_geodetic_spheroid(self):
  295. tol = 2 if oracle else 4
  296. # Got the reference distances using the raw SQL statements:
  297. # SELECT ST_distance_spheroid(point, ST_GeomFromText('POINT(151.231341 -33.952685)', 4326),
  298. # 'SPHEROID["WGS 84",6378137.0,298.257223563]') FROM distapp_australiacity WHERE (NOT (id = 11));
  299. # SELECT ST_distance_sphere(point, ST_GeomFromText('POINT(151.231341 -33.952685)', 4326))
  300. # FROM distapp_australiacity WHERE (NOT (id = 11)); st_distance_sphere
  301. spheroid_distances = [
  302. 60504.0628957201, 77023.9489850262, 49154.8867574404,
  303. 90847.4358768573, 217402.811919332, 709599.234564757,
  304. 640011.483550888, 7772.00667991925, 1047861.78619339,
  305. 1165126.55236034,
  306. ]
  307. sphere_distances = [
  308. 60580.9693849267, 77144.0435286473, 49199.4415344719,
  309. 90804.7533823494, 217713.384600405, 709134.127242793,
  310. 639828.157159169, 7786.82949717788, 1049204.06569028,
  311. 1162623.7238134,
  312. ]
  313. # Testing with spheroid distances first.
  314. hillsdale = AustraliaCity.objects.get(name='Hillsdale')
  315. qs = AustraliaCity.objects.exclude(id=hillsdale.id).annotate(
  316. distance=Distance('point', hillsdale.point, spheroid=True)
  317. ).order_by('id')
  318. for i, c in enumerate(qs):
  319. with self.subTest(c=c):
  320. self.assertAlmostEqual(spheroid_distances[i], c.distance.m, tol)
  321. if postgis or spatialite:
  322. # PostGIS uses sphere-only distances by default, testing these as well.
  323. qs = AustraliaCity.objects.exclude(id=hillsdale.id).annotate(
  324. distance=Distance('point', hillsdale.point)
  325. ).order_by('id')
  326. for i, c in enumerate(qs):
  327. with self.subTest(c=c):
  328. self.assertAlmostEqual(sphere_distances[i], c.distance.m, tol)
  329. @skipIfDBFeature("supports_distance_geodetic")
  330. @skipUnlessDBFeature("has_Distance_function")
  331. def test_distance_function_raw_result(self):
  332. distance = Interstate.objects.annotate(
  333. d=Distance(Point(0, 0, srid=4326), Point(0, 1, srid=4326)),
  334. ).first().d
  335. self.assertEqual(distance, 1)
  336. @skipUnlessDBFeature("has_Distance_function")
  337. def test_distance_function_d_lookup(self):
  338. qs = Interstate.objects.annotate(
  339. d=Distance(Point(0, 0, srid=3857), Point(0, 1, srid=3857)),
  340. ).filter(d=D(m=1))
  341. self.assertTrue(qs.exists())
  342. @skipIfDBFeature("supports_distance_geodetic")
  343. @skipUnlessDBFeature("has_Distance_function")
  344. def test_distance_function_raw_result_d_lookup(self):
  345. qs = Interstate.objects.annotate(
  346. d=Distance(Point(0, 0, srid=4326), Point(0, 1, srid=4326)),
  347. ).filter(d=D(m=1))
  348. msg = 'Distance measure is supplied, but units are unknown for result.'
  349. with self.assertRaisesMessage(ValueError, msg):
  350. list(qs)
  351. @no_oracle # Oracle already handles geographic distance calculation.
  352. @skipUnlessDBFeature("has_Distance_function", 'has_Transform_function')
  353. def test_distance_transform(self):
  354. """
  355. Test the `Distance` function used with `Transform` on a geographic field.
  356. """
  357. # We'll be using a Polygon (created by buffering the centroid
  358. # of 77005 to 100m) -- which aren't allowed in geographic distance
  359. # queries normally, however our field has been transformed to
  360. # a non-geographic system.
  361. z = SouthTexasZipcode.objects.get(name='77005')
  362. # Reference query:
  363. # SELECT ST_Distance(ST_Transform("distapp_censuszipcode"."poly", 32140),
  364. # ST_GeomFromText('<buffer_wkt>', 32140))
  365. # FROM "distapp_censuszipcode";
  366. dists_m = [3553.30384972258, 1243.18391525602, 2186.15439472242]
  367. # Having our buffer in the SRID of the transformation and of the field
  368. # -- should get the same results. The first buffer has no need for
  369. # transformation SQL because it is the same SRID as what was given
  370. # to `transform()`. The second buffer will need to be transformed,
  371. # however.
  372. buf1 = z.poly.centroid.buffer(100)
  373. buf2 = buf1.transform(4269, clone=True)
  374. ref_zips = ['77002', '77025', '77401']
  375. for buf in [buf1, buf2]:
  376. qs = CensusZipcode.objects.exclude(name='77005').annotate(
  377. distance=Distance(Transform('poly', 32140), buf)
  378. ).order_by('name')
  379. self.assertEqual(ref_zips, sorted(c.name for c in qs))
  380. for i, z in enumerate(qs):
  381. self.assertAlmostEqual(z.distance.m, dists_m[i], 5)
  382. @skipUnlessDBFeature("has_Distance_function")
  383. def test_distance_order_by(self):
  384. qs = SouthTexasCity.objects.annotate(distance=Distance('point', Point(3, 3, srid=32140))).order_by(
  385. 'distance'
  386. ).values_list('name', flat=True).filter(name__in=('San Antonio', 'Pearland'))
  387. self.assertSequenceEqual(qs, ['San Antonio', 'Pearland'])
  388. @skipUnlessDBFeature("has_Length_function")
  389. def test_length(self):
  390. """
  391. Test the `Length` function.
  392. """
  393. # Reference query (should use `length_spheroid`).
  394. # SELECT ST_length_spheroid(ST_GeomFromText('<wkt>', 4326) 'SPHEROID["WGS 84",6378137,298.257223563,
  395. # AUTHORITY["EPSG","7030"]]');
  396. len_m1 = 473504.769553813
  397. len_m2 = 4617.668
  398. if connection.features.supports_length_geodetic:
  399. qs = Interstate.objects.annotate(length=Length('path'))
  400. tol = 2 if oracle else 3
  401. self.assertAlmostEqual(len_m1, qs[0].length.m, tol)
  402. # TODO: test with spheroid argument (True and False)
  403. else:
  404. # Does not support geodetic coordinate systems.
  405. with self.assertRaises(NotImplementedError):
  406. list(Interstate.objects.annotate(length=Length('path')))
  407. # Now doing length on a projected coordinate system.
  408. i10 = SouthTexasInterstate.objects.annotate(length=Length('path')).get(name='I-10')
  409. self.assertAlmostEqual(len_m2, i10.length.m, 2)
  410. self.assertTrue(
  411. SouthTexasInterstate.objects.annotate(length=Length('path')).filter(length__gt=4000).exists()
  412. )
  413. # Length with an explicit geometry value.
  414. qs = Interstate.objects.annotate(length=Length(i10.path))
  415. self.assertAlmostEqual(qs.first().length.m, len_m2, 2)
  416. @skipUnlessDBFeature("has_Perimeter_function")
  417. def test_perimeter(self):
  418. """
  419. Test the `Perimeter` function.
  420. """
  421. # Reference query:
  422. # SELECT ST_Perimeter(distapp_southtexaszipcode.poly) FROM distapp_southtexaszipcode;
  423. perim_m = [18404.3550889361, 15627.2108551001, 20632.5588368978, 17094.5996143697]
  424. tol = 2 if oracle else 7
  425. qs = SouthTexasZipcode.objects.annotate(perimeter=Perimeter('poly')).order_by('name')
  426. for i, z in enumerate(qs):
  427. self.assertAlmostEqual(perim_m[i], z.perimeter.m, tol)
  428. # Running on points; should return 0.
  429. qs = SouthTexasCity.objects.annotate(perim=Perimeter('point'))
  430. for city in qs:
  431. self.assertEqual(0, city.perim.m)
  432. @skipUnlessDBFeature("has_Perimeter_function")
  433. def test_perimeter_geodetic(self):
  434. # Currently only Oracle supports calculating the perimeter on geodetic
  435. # geometries (without being transformed).
  436. qs1 = CensusZipcode.objects.annotate(perim=Perimeter('poly'))
  437. if connection.features.supports_perimeter_geodetic:
  438. self.assertAlmostEqual(qs1[0].perim.m, 18406.3818954314, 3)
  439. else:
  440. with self.assertRaises(NotImplementedError):
  441. list(qs1)
  442. # But should work fine when transformed to projected coordinates
  443. qs2 = CensusZipcode.objects.annotate(perim=Perimeter(Transform('poly', 32140))).filter(name='77002')
  444. self.assertAlmostEqual(qs2[0].perim.m, 18404.355, 3)
  445. @skipUnlessDBFeature("supports_null_geometries", "has_Area_function", "has_Distance_function")
  446. def test_measurement_null_fields(self):
  447. """
  448. Test the measurement functions on fields with NULL values.
  449. """
  450. # Creating SouthTexasZipcode w/NULL value.
  451. SouthTexasZipcode.objects.create(name='78212')
  452. # Performing distance/area queries against the NULL PolygonField,
  453. # and ensuring the result of the operations is None.
  454. htown = SouthTexasCity.objects.get(name='Downtown Houston')
  455. z = SouthTexasZipcode.objects.annotate(
  456. distance=Distance('poly', htown.point), area=Area('poly')
  457. ).get(name='78212')
  458. self.assertIsNone(z.distance)
  459. self.assertIsNone(z.area)