Debian Codegraph @

docs/ref/contrib/gis/tutorial.txt

raw
1 ==================
2 GeoDjango Tutorial
3 ==================
4
5 Introduction
6 ============
7
8 GeoDjango is an included contrib module for Django that turns it into a
9 world-class geographic web framework. GeoDjango strives to make it as simple
10 as possible to create geographic web applications, like location-based services.
11 Its features include:
12
13 * Django model fields for `OGC`_ geometries and raster data.
14 * Extensions to Django's ORM for querying and manipulating spatial data.
15 * Loosely-coupled, high-level Python interfaces for GIS geometry and raster
16 operations and data manipulation in different formats.
17 * Editing geometry fields from the admin.
18
19 This tutorial assumes familiarity with Django; thus, if you're brand new to
20 Django, please read through the :doc:`regular tutorial </intro/tutorial01>` to
21 familiarize yourself with Django first.
22
23 .. note::
24
25 GeoDjango has additional requirements beyond what Django requires --
26 please consult the :doc:`installation documentation <install/index>`
27 for more details.
28
29 This tutorial will guide you through the creation of a geographic web
30 application for viewing the `world borders`_. [#]_ Some of the code
31 used in this tutorial is taken from and/or inspired by the `GeoDjango
32 basic apps`_ project. [#]_
33
34 .. note::
35
36 Proceed through the tutorial sections sequentially for step-by-step
37 instructions.
38
39 .. _OGC: https://www.ogc.org/
40 .. _world borders: https://web.archive.org/web/20240123190237/https://thematicmapping.org/downloads/world_borders.php
41 .. _GeoDjango basic apps: https://code.google.com/archive/p/geodjango-basic-apps
42
43 Setting Up
44 ==========
45
46 Create a Spatial Database
47 -------------------------
48
49 Typically no special setup is required, so you can create a database as you
50 would for any other project. We provide some tips for selected databases:
51
52 * :doc:`install/postgis`
53 * :doc:`install/spatialite`
54
55 Create a New Project
56 --------------------
57
58 Use the standard ``django-admin`` script to create a project called
59 ``geodjango``:
60
61 .. console::
62
63 $ django-admin startproject geodjango
64
65 This will initialize a new project. Now, create a ``world`` Django application
66 within the ``geodjango`` project:
67
68 .. console::
69
70 $ cd geodjango
71 $ python manage.py startapp world
72
73 Configure ``settings.py``
74 -------------------------
75
76 The ``geodjango`` project settings are stored in the ``geodjango/settings.py``
77 file. Edit the database connection settings to match your setup::
78
79 DATABASES = {
80 "default": {
81 "ENGINE": "django.contrib.gis.db.backends.postgis",
82 "NAME": "geodjango",
83 "USER": "geo",
84 },
85 }
86
87 In addition, modify the :setting:`INSTALLED_APPS` setting to include
88 :mod:`django.contrib.admin`, :mod:`django.contrib.gis`,
89 and ``world`` (your newly created application)::
90
91 INSTALLED_APPS = [
92 "django.contrib.admin",
93 "django.contrib.auth",
94 "django.contrib.contenttypes",
95 "django.contrib.sessions",
96 "django.contrib.messages",
97 "django.contrib.staticfiles",
98 "django.contrib.gis",
99 "world",
100 ]
101
102 Geographic Data
103 ===============
104
105 .. _worldborders:
106
107 World Borders
108 -------------
109
110 The world borders data is available in this `zip file`__. Create a ``data``
111 directory in the ``world`` application, download the world borders data, and
112 unzip. On GNU/Linux platforms, use the following commands:
113
114 .. console::
115
116 $ mkdir world/data
117 $ cd world/data
118 $ wget https://web.archive.org/web/20231220150759/https://thematicmapping.org/downloads/TM_WORLD_BORDERS-0.3.zip
119 $ unzip TM_WORLD_BORDERS-0.3.zip
120 $ cd ../..
121
122 The world borders ZIP file contains a set of data files collectively known as
123 an `ESRI Shapefile`__, one of the most popular geospatial data formats. When
124 unzipped, the world borders dataset includes files with the following
125 extensions:
126
127 * ``.shp``: Holds the vector data for the world borders geometries.
128 * ``.shx``: Spatial index file for geometries stored in the ``.shp``.
129 * ``.dbf``: Database file for holding non-geometric attribute data
130 (e.g., integer and character fields).
131 * ``.prj``: Contains the spatial reference information for the geographic
132 data stored in the shapefile.
133
134 __ https://web.archive.org/web/20231220150759/https://thematicmapping.org/downloads/TM_WORLD_BORDERS-0.3.zip
135 __ https://en.wikipedia.org/wiki/Shapefile
136
137 Use ``ogrinfo`` to examine spatial data
138 ---------------------------------------
139
140 The GDAL ``ogrinfo`` utility allows examining the metadata of shapefiles or
141 other vector data sources:
142
143 .. console::
144
145 $ ogrinfo world/data/TM_WORLD_BORDERS-0.3.shp
146 INFO: Open of `world/data/TM_WORLD_BORDERS-0.3.shp'
147 using driver `ESRI Shapefile' successful.
148 1: TM_WORLD_BORDERS-0.3 (Polygon)
149
150 ``ogrinfo`` tells us that the shapefile has one layer, and that this
151 layer contains polygon data. To find out more, we'll specify the layer name
152 and use the ``-so`` option to get only the important summary information:
153
154 .. console::
155
156 $ ogrinfo -so world/data/TM_WORLD_BORDERS-0.3.shp TM_WORLD_BORDERS-0.3
157 INFO: Open of `world/data/TM_WORLD_BORDERS-0.3.shp'
158 using driver `ESRI Shapefile' successful.
159
160 Layer name: TM_WORLD_BORDERS-0.3
161 Metadata:
162 DBF_DATE_LAST_UPDATE=2008-07-30
163 Geometry: Polygon
164 Feature Count: 246
165 Extent: (-180.000000, -90.000000) - (180.000000, 83.623596)
166 Layer SRS WKT:
167 GEOGCRS["WGS 84",
168 DATUM["World Geodetic System 1984",
169 ELLIPSOID["WGS 84",6378137,298.257223563,
170 LENGTHUNIT["metre",1]]],
171 PRIMEM["Greenwich",0,
172 ANGLEUNIT["degree",0.0174532925199433]],
173 CS[ellipsoidal,2],
174 AXIS["latitude",north,
175 ORDER[1],
176 ANGLEUNIT["degree",0.0174532925199433]],
177 AXIS["longitude",east,
178 ORDER[2],
179 ANGLEUNIT["degree",0.0174532925199433]],
180 ID["EPSG",4326]]
181 Data axis to CRS axis mapping: 2,1
182 FIPS: String (2.0)
183 ISO2: String (2.0)
184 ISO3: String (3.0)
185 UN: Integer (3.0)
186 NAME: String (50.0)
187 AREA: Integer (7.0)
188 POP2005: Integer64 (10.0)
189 REGION: Integer (3.0)
190 SUBREGION: Integer (3.0)
191 LON: Real (8.3)
192 LAT: Real (7.3)
193
194 This detailed summary information tells us the number of features in the layer
195 (246), the geographic bounds of the data, the spatial reference system
196 ("SRS WKT"), as well as type information for each attribute field. For example,
197 ``FIPS: String (2.0)`` indicates that the ``FIPS`` character field has
198 a maximum length of 2. Similarly, ``LON: Real (8.3)`` is a floating-point
199 field that holds a maximum of 8 digits up to three decimal places.
200
201 Geographic Models
202 =================
203
204 Defining a Geographic Model
205 ---------------------------
206
207 Now that you've examined your dataset using ``ogrinfo``, create a GeoDjango
208 model to represent this data::
209
210 from django.contrib.gis.db import models
211
212
213 class WorldBorder(models.Model):
214 # Regular Django fields corresponding to the attributes in the
215 # world borders shapefile.
216 name = models.CharField(max_length=50)
217 area = models.IntegerField()
218 pop2005 = models.IntegerField("Population 2005")
219 fips = models.CharField("FIPS Code", max_length=2, null=True)
220 iso2 = models.CharField("2 Digit ISO", max_length=2)
221 iso3 = models.CharField("3 Digit ISO", max_length=3)
222 un = models.IntegerField("United Nations Code")
223 region = models.IntegerField("Region Code")
224 subregion = models.IntegerField("Sub-Region Code")
225 lon = models.FloatField()
226 lat = models.FloatField()
227
228 # GeoDjango-specific: a geometry field (MultiPolygonField)
229 mpoly = models.MultiPolygonField()
230
231 # Returns the string representation of the model.
232 def __str__(self):
233 return self.name
234
235 Note that the ``models`` module is imported from ``django.contrib.gis.db``.
236
237 The default spatial reference system for geometry fields is WGS84 (meaning
238 the `SRID`__ is 4326) -- in other words, the field coordinates are in
239 longitude, latitude pairs in units of degrees. To use a different
240 coordinate system, set the SRID of the geometry field with the ``srid``
241 argument. Use an integer representing the coordinate system's EPSG code.
242
243 __ https://en.wikipedia.org/wiki/SRID
244
245 Run ``migrate``
246 ---------------
247
248 After defining your model, you need to sync it with the database. First,
249 create a database migration:
250
251 .. console::
252
253 $ python manage.py makemigrations
254 Migrations for 'world':
255 world/migrations/0001_initial.py:
256 + Create model WorldBorder
257
258 Let's look at the SQL that will generate the table for the ``WorldBorder``
259 model:
260
261 .. console::
262
263 $ python manage.py sqlmigrate world 0001
264
265 This command should produce the following output:
266
267 .. code-block:: sql
268
269 BEGIN;
270 --
271 -- Create model WorldBorder
272 --
273 CREATE TABLE "world_worldborder" (
274 "id" bigint NOT NULL PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
275 "name" varchar(50) NOT NULL,
276 "area" integer NOT NULL,
277 "pop2005" integer NOT NULL,
278 "fips" varchar(2) NOT NULL,
279 "iso2" varchar(2) NOT NULL,
280 "iso3" varchar(3) NOT NULL,
281 "un" integer NOT NULL,
282 "region" integer NOT NULL,
283 "subregion" integer NOT NULL,
284 "lon" double precision NOT NULL,
285 "lat" double precision NOT NULL
286 "mpoly" geometry(MULTIPOLYGON,4326) NOT NULL
287 )
288 ;
289 CREATE INDEX "world_worldborder_mpoly_id" ON "world_worldborder" USING GIST ("mpoly");
290 COMMIT;
291
292 If this looks correct, run :djadmin:`migrate` to create this table in the
293 database:
294
295 .. console::
296
297 $ python manage.py migrate
298 Operations to perform:
299 Apply all migrations: admin, auth, contenttypes, sessions, world
300 Running migrations:
301 ...
302 Applying world.0001_initial... OK
303
304 Importing Spatial Data
305 ======================
306
307 This section will show you how to import the world borders shapefile into the
308 database via GeoDjango models using the :doc:`layermapping`.
309
310 There are many different ways to import data into a spatial database --
311 besides the tools included within GeoDjango, you may also use the following:
312
313 * `ogr2ogr`_: A command-line utility included with GDAL that
314 can import many vector data formats into PostGIS, MySQL, and Oracle databases.
315 * `shp2pgsql`_: This utility included with PostGIS imports ESRI shapefiles into
316 PostGIS.
317
318 .. _ogr2ogr: https://gdal.org/programs/ogr2ogr.html
319 .. _shp2pgsql: https://postgis.net/docs/using_postgis_dbmanagement.html#shp2pgsql_usage
320
321 .. _gdalinterface:
322
323 GDAL Interface
324 --------------
325
326 Earlier, you used ``ogrinfo`` to examine the contents of the world borders
327 shapefile. GeoDjango also includes a Pythonic interface to GDAL's powerful OGR
328 library that can work with all the vector data sources that OGR supports.
329
330 First, invoke the Django shell:
331
332 .. console::
333
334 $ python manage.py shell
335
336 If you downloaded the :ref:`worldborders` data earlier in the tutorial, then
337 you can determine its path using Python's :class:`pathlib.Path`:
338
339 .. code-block:: pycon
340
341 >>> from pathlib import Path
342 >>> import world
343 >>> world_shp = Path(world.__file__).resolve().parent / "data" / "TM_WORLD_BORDERS-0.3.shp"
344
345 Now, open the world borders shapefile using GeoDjango's
346 :class:`~django.contrib.gis.gdal.DataSource` interface:
347
348 .. code-block:: pycon
349
350 >>> from django.contrib.gis.gdal import DataSource
351 >>> ds = DataSource(world_shp)
352 >>> print(ds)
353 / ... /geodjango/world/data/TM_WORLD_BORDERS-0.3.shp (ESRI Shapefile)
354
355 Data source objects can have different layers of geospatial features; however,
356 shapefiles are only allowed to have one layer:
357
358 .. code-block:: pycon
359
360 >>> print(len(ds))
361 1
362 >>> lyr = ds[0]
363 >>> print(lyr)
364 TM_WORLD_BORDERS-0.3
365
366 You can see the layer's geometry type and how many features it contains:
367
368 .. code-block:: pycon
369
370 >>> print(lyr.geom_type)
371 Polygon
372 >>> print(len(lyr))
373 246
374
375 .. note::
376
377 Unfortunately, the shapefile data format does not allow for greater
378 specificity with regards to geometry types. This shapefile, like
379 many others, actually includes ``MultiPolygon`` geometries, not Polygons.
380 It's important to use a more general field type in models: a
381 GeoDjango ``MultiPolygonField`` will accept a ``Polygon`` geometry, but a
382 ``PolygonField`` will not accept a ``MultiPolygon`` type geometry. This
383 is why the ``WorldBorder`` model defined above uses a ``MultiPolygonField``.
384
385 The :class:`~django.contrib.gis.gdal.Layer` may also have a spatial reference
386 system associated with it. If it does, the ``srs`` attribute will return a
387 :class:`~django.contrib.gis.gdal.SpatialReference` object:
388
389 .. code-block:: pycon
390
391 >>> srs = lyr.srs
392 >>> print(srs)
393 GEOGCS["WGS 84",
394 DATUM["WGS_1984",
395 SPHEROID["WGS 84",6378137,298.257223563,
396 AUTHORITY["EPSG","7030"]],
397 AUTHORITY["EPSG","6326"]],
398 PRIMEM["Greenwich",0,
399 AUTHORITY["EPSG","8901"]],
400 UNIT["degree",0.0174532925199433,
401 AUTHORITY["EPSG","9122"]],
402 AXIS["Latitude",NORTH],
403 AXIS["Longitude",EAST],
404 AUTHORITY["EPSG","4326"]]
405 >>> srs.proj # PROJ representation
406 '+proj=longlat +datum=WGS84 +no_defs'
407
408 This shapefile is in the popular WGS84 spatial reference
409 system -- in other words, the data uses longitude, latitude pairs in
410 units of degrees.
411
412 In addition, shapefiles also support attribute fields that may contain
413 additional data. Here are the fields on the World Borders layer:
414
415 >>> print(lyr.fields)
416 ['FIPS', 'ISO2', 'ISO3', 'UN', 'NAME', 'AREA', 'POP2005', 'REGION', 'SUBREGION', 'LON', 'LAT']
417
418 The following code will let you examine the OGR types (e.g. integer or
419 string) associated with each of the fields:
420
421 >>> [fld.__name__ for fld in lyr.field_types]
422 ['OFTString', 'OFTString', 'OFTString', 'OFTInteger', 'OFTString', 'OFTInteger', 'OFTInteger64', 'OFTInteger', 'OFTInteger', 'OFTReal', 'OFTReal']
423
424 You can iterate over each feature in the layer and extract information from both
425 the feature's geometry (accessed via the ``geom`` attribute) as well as the
426 feature's attribute fields (whose **values** are accessed via ``get()``
427 method):
428
429 .. code-block:: pycon
430
431 >>> for feat in lyr:
432 ... print(feat.get("NAME"), feat.geom.num_points)
433 ...
434 Guernsey 18
435 Jersey 26
436 South Georgia South Sandwich Islands 338
437 Taiwan 363
438
439 :class:`~django.contrib.gis.gdal.Layer` objects may be sliced:
440
441 .. code-block:: pycon
442
443 >>> lyr[0:2]
444 [<django.contrib.gis.gdal.feature.Feature object at 0x2f47690>, <django.contrib.gis.gdal.feature.Feature object at 0x2f47650>]
445
446 And individual features may be retrieved by their feature ID:
447
448 .. code-block:: pycon
449
450 >>> feat = lyr[234]
451 >>> print(feat.get("NAME"))
452 San Marino
453
454 Boundary geometries may be exported as WKT and GeoJSON:
455
456 .. code-block:: pycon
457
458 >>> geom = feat.geom
459 >>> print(geom.wkt)
460 POLYGON ((12.415798 43.957954,12.450554 ...
461 >>> print(geom.json)
462 { "type": "Polygon", "coordinates": [ [ [ 12.415798, 43.957954 ], [ 12.450554, 43.979721 ], ...
463
464 ``LayerMapping``
465 ----------------
466
467 To import the data, use a ``LayerMapping`` in a Python script.
468 Create a file called ``load.py`` inside the ``world`` application,
469 with the following code::
470
471 from pathlib import Path
472 from django.contrib.gis.utils import LayerMapping
473 from .models import WorldBorder
474
475 world_mapping = {
476 "fips": "FIPS",
477 "iso2": "ISO2",
478 "iso3": "ISO3",
479 "un": "UN",
480 "name": "NAME",
481 "area": "AREA",
482 "pop2005": "POP2005",
483 "region": "REGION",
484 "subregion": "SUBREGION",
485 "lon": "LON",
486 "lat": "LAT",
487 "mpoly": "MULTIPOLYGON",
488 }
489
490 world_shp = Path(__file__).resolve().parent / "data" / "TM_WORLD_BORDERS-0.3.shp"
491
492
493 def run(verbose=True):
494 lm = LayerMapping(WorldBorder, world_shp, world_mapping, transform=False)
495 lm.save(strict=True, verbose=verbose)
496
497 A few notes about what's going on:
498
499 * Each key in the ``world_mapping`` dictionary corresponds to a field in the
500 ``WorldBorder`` model. The value is the name of the shapefile field
501 that data will be loaded from.
502 * The key ``mpoly`` for the geometry field is ``MULTIPOLYGON``, the
503 geometry type GeoDjango will import the field as. Even simple polygons in
504 the shapefile will automatically be converted into collections prior to
505 insertion into the database.
506 * The path to the shapefile is not absolute -- in other words, if you move the
507 ``world`` application (with ``data`` subdirectory) to a different location,
508 the script will still work.
509 * The ``transform`` keyword is set to ``False`` because the data in the
510 shapefile does not need to be converted -- it's already in WGS84 (SRID=4326).
511
512 Afterward, invoke the Django shell from the ``geodjango`` project directory:
513
514 .. console::
515
516 $ python manage.py shell
517
518 Next, import the ``load`` module, call the ``run`` routine, and watch
519 ``LayerMapping`` do the work:
520
521 .. code-block:: pycon
522
523 >>> from world import load
524 >>> load.run()
525
526 .. _ogrinspect-intro:
527
528 Try ``ogrinspect``
529 ------------------
530 Now that you've seen how to define geographic models and import data with the
531 :doc:`layermapping`, it's possible to further automate this process with
532 use of the :djadmin:`ogrinspect` management command. The :djadmin:`ogrinspect`
533 command introspects a GDAL-supported vector data source (e.g., a shapefile)
534 and generates a model definition and ``LayerMapping`` dictionary automatically.
535
536 The general usage of the command goes as follows:
537
538 .. console::
539
540 $ python manage.py ogrinspect [options] <data_source> <model_name> [options]
541
542 ``data_source`` is the path to the GDAL-supported data source and
543 ``model_name`` is the name to use for the model. Command-line options may
544 be used to further define how the model is generated.
545
546 For example, the following command nearly reproduces the ``WorldBorder`` model
547 and mapping dictionary created above, automatically:
548
549 .. console::
550
551 $ python manage.py ogrinspect world/data/TM_WORLD_BORDERS-0.3.shp WorldBorder \
552 --srid=4326 --mapping --multi
553
554 A few notes about the command-line options given above:
555
556 * The ``--srid=4326`` option sets the SRID for the geographic field.
557 * The ``--mapping`` option tells ``ogrinspect`` to also generate a
558 mapping dictionary for use with
559 :class:`~django.contrib.gis.utils.LayerMapping`.
560 * The ``--multi`` option is specified so that the geographic field is a
561 :class:`~django.contrib.gis.db.models.MultiPolygonField` instead of just a
562 :class:`~django.contrib.gis.db.models.PolygonField`.
563
564 The command produces the following output, which may be copied
565 directly into the ``models.py`` of a GeoDjango application::
566
567 # This is an auto-generated Django model module created by ogrinspect.
568 from django.contrib.gis.db import models
569
570
571 class WorldBorder(models.Model):
572 fips = models.CharField(max_length=2)
573 iso2 = models.CharField(max_length=2)
574 iso3 = models.CharField(max_length=3)
575 un = models.IntegerField()
576 name = models.CharField(max_length=50)
577 area = models.IntegerField()
578 pop2005 = models.IntegerField()
579 region = models.IntegerField()
580 subregion = models.IntegerField()
581 lon = models.FloatField()
582 lat = models.FloatField()
583 geom = models.MultiPolygonField(srid=4326)
584
585
586 # Auto-generated `LayerMapping` dictionary for WorldBorder model
587 worldborders_mapping = {
588 "fips": "FIPS",
589 "iso2": "ISO2",
590 "iso3": "ISO3",
591 "un": "UN",
592 "name": "NAME",
593 "area": "AREA",
594 "pop2005": "POP2005",
595 "region": "REGION",
596 "subregion": "SUBREGION",
597 "lon": "LON",
598 "lat": "LAT",
599 "geom": "MULTIPOLYGON",
600 }
601
602 Spatial Queries
603 ===============
604
605 Spatial Lookups
606 ---------------
607 GeoDjango adds spatial lookups to the Django ORM. For example, you
608 can find the country in the ``WorldBorder`` table that contains
609 a particular point. First, fire up the management shell:
610
611 .. console::
612
613 $ python manage.py shell
614
615 Now, define a point of interest [#]_:
616
617 .. code-block:: pycon
618
619 >>> pnt_wkt = "POINT(-95.3385 29.7245)"
620
621 The ``pnt_wkt`` string represents the point at -95.3385 degrees longitude,
622 29.7245 degrees latitude. The geometry is in a format known as
623 Well Known Text (WKT), a standard issued by the Open Geospatial
624 Consortium (OGC). [#]_ Import the ``WorldBorder`` model, and perform
625 a ``contains`` lookup using the ``pnt_wkt`` as the parameter:
626
627 .. code-block:: pycon
628
629 >>> from world.models import WorldBorder
630 >>> WorldBorder.objects.filter(mpoly__contains=pnt_wkt)
631 <QuerySet [<WorldBorder: United States>]>
632
633 Here, you retrieved a ``QuerySet`` with only one model: the border of the
634 United States (exactly what you would expect).
635
636 Similarly, you may also use a :doc:`GEOS geometry object <geos>`.
637 Here, you can combine the ``intersects`` spatial lookup with the ``get``
638 method to retrieve only the ``WorldBorder`` instance for San Marino instead
639 of a queryset:
640
641 .. code-block:: pycon
642
643 >>> from django.contrib.gis.geos import Point
644 >>> pnt = Point(12.4604, 43.9420)
645 >>> WorldBorder.objects.get(mpoly__intersects=pnt)
646 <WorldBorder: San Marino>
647
648 The ``contains`` and ``intersects`` lookups are just a subset of the
649 available queries -- the :doc:`db-api` documentation has more.
650
651 .. _automatic-spatial-transformations:
652
653 Automatic Spatial Transformations
654 ---------------------------------
655 When doing spatial queries, GeoDjango automatically transforms
656 geometries if they're in a different coordinate system. In the following
657 example, coordinates will be expressed in `EPSG SRID 32140`__,
658 a coordinate system specific to south Texas **only** and in units of
659 **meters**, not degrees:
660
661 .. code-block:: pycon
662
663 >>> from django.contrib.gis.geos import GEOSGeometry, Point
664 >>> pnt = Point(954158.1, 4215137.1, srid=32140)
665
666 Note that ``pnt`` may also be constructed with EWKT, an "extended" form of
667 WKT that includes the SRID:
668
669 .. code-block:: pycon
670
671 >>> pnt = GEOSGeometry("SRID=32140;POINT(954158.1 4215137.1)")
672
673 GeoDjango's ORM will automatically wrap geometry values
674 in transformation SQL, allowing the developer to work at a higher level
675 of abstraction:
676
677 .. code-block:: pycon
678
679 >>> qs = WorldBorder.objects.filter(mpoly__intersects=pnt)
680 >>> print(qs.query) # Generating the SQL
681 SELECT "world_worldborder"."id", "world_worldborder"."name", "world_worldborder"."area",
682 "world_worldborder"."pop2005", "world_worldborder"."fips", "world_worldborder"."iso2",
683 "world_worldborder"."iso3", "world_worldborder"."un", "world_worldborder"."region",
684 "world_worldborder"."subregion", "world_worldborder"."lon", "world_worldborder"."lat",
685 "world_worldborder"."mpoly" FROM "world_worldborder"
686 WHERE ST_Intersects("world_worldborder"."mpoly", ST_Transform(%s, 4326))
687 >>> qs # printing evaluates the queryset
688 <QuerySet [<WorldBorder: United States>]>
689
690 __ https://spatialreference.org/ref/epsg/32140/
691
692 .. _gis-raw-sql:
693
694 .. admonition:: Raw queries
695
696 When using :doc:`raw queries </topics/db/sql>`, you must wrap your geometry
697 fields so that the field value can be recognized by GEOS:
698
699 .. code-block:: pycon
700
701 >>> from django.db import connection
702 >>> # or if you're querying a non-default database:
703 >>> from django.db import connections
704 >>> connection = connections["your_gis_db_alias"]
705 >>> City.objects.raw(
706 ... "SELECT id, name, %s as point from myapp_city" % (connection.ops.select % "point")
707 ... )
708
709 You should only use raw queries when you know exactly what you're doing.
710
711 Lazy Geometries
712 ---------------
713 GeoDjango loads geometries in a standardized textual representation. When the
714 geometry field is first accessed, GeoDjango creates a
715 :class:`~django.contrib.gis.geos.GEOSGeometry` object, exposing powerful
716 functionality, such as serialization properties for popular geospatial
717 formats:
718
719 .. code-block:: pycon
720
721 >>> sm = WorldBorder.objects.get(name="San Marino")
722 >>> sm.mpoly
723 <MultiPolygon object at 0x24c6798>
724 >>> sm.mpoly.wkt # WKT
725 MULTIPOLYGON (((12.4157980000000006 43.9579540000000009, 12.4505540000000003 43.9797209999999978, ...
726 >>> sm.mpoly.wkb # WKB (as Python binary buffer)
727 <read-only buffer for 0x1fe2c70, size -1, offset 0 at 0x2564c40>
728 >>> sm.mpoly.geojson # GeoJSON
729 '{ "type": "MultiPolygon", "coordinates": [ [ [ [ 12.415798, 43.957954 ], [ 12.450554, 43.979721 ], ...
730
731 This includes access to all of the advanced geometric operations provided by
732 the GEOS library:
733
734 .. code-block:: pycon
735
736 >>> pnt = Point(12.4604, 43.9420)
737 >>> sm.mpoly.contains(pnt)
738 True
739 >>> pnt.contains(sm.mpoly)
740 False
741
742 Geographic annotations
743 ----------------------
744
745 GeoDjango also offers a set of geographic annotations to compute distances and
746 several other operations (intersection, difference, etc.). See the
747 :doc:`functions` documentation.
748
749 Putting your data on the map
750 ============================
751
752 Geographic Admin
753 ----------------
754
755 :doc:`Django's admin application </ref/contrib/admin/index>` supports editing
756 geometry fields.
757
758 Basics
759 ~~~~~~
760
761 The Django admin allows users to create and modify geometries on a JavaScript
762 slippy map (powered by `OpenLayers`_).
763
764 Let's dive right in. Create a file called ``admin.py`` inside the ``world``
765 application with the following code::
766
767 from django.contrib.gis import admin
768 from .models import WorldBorder
769
770 admin.site.register(WorldBorder, admin.ModelAdmin)
771
772 Next, edit your ``urls.py`` in the ``geodjango`` application folder as follows::
773
774 from django.contrib import admin
775 from django.urls import include, path
776
777 urlpatterns = [
778 path("admin/", admin.site.urls),
779 ]
780
781 Create an admin user:
782
783 .. console::
784
785 $ python manage.py createsuperuser
786
787 Next, start up the Django development server:
788
789 .. console::
790
791 $ python manage.py runserver
792
793 Finally, browse to ``http://localhost:8000/admin/``, and log in with the user
794 you just created. Browse to any of the ``WorldBorder`` entries -- the borders
795 may be edited by clicking on a polygon and dragging the vertices to the desired
796 position.
797
798 .. _OpenLayers: https://openlayers.org/
799 .. _OpenStreetMap: https://www.openstreetmap.org/
800 .. _Vector Map Level 0: http://web.archive.org/web/20201024202709/https://earth-info.nga.mil/publications/vmap0.html
801 .. _OSGeo: https://www.osgeo.org/
802
803 ``GISModelAdmin``
804 ~~~~~~~~~~~~~~~~~
805
806 With the :class:`~django.contrib.gis.admin.GISModelAdmin`, GeoDjango uses an
807 `OpenStreetMap`_ layer in the admin.
808 This provides more context (including street and thoroughfare details) than
809 available with the :class:`~django.contrib.admin.ModelAdmin` (which uses the
810 `Vector Map Level 0`_ WMS dataset hosted at `OSGeo`_).
811
812 The PROJ datum shifting files must be installed (see the :ref:`PROJ
813 installation instructions <proj4>` for more details).
814
815 If you meet this requirement, then use the ``GISModelAdmin`` option class
816 in your ``admin.py`` file::
817
818 admin.site.register(WorldBorder, admin.GISModelAdmin)
819
820 .. rubric:: Footnotes
821
822 .. [#] Special thanks to Bjørn Sandvik of `mastermaps.net
823 <https://mastermaps.net/>`_ for providing and maintaining this dataset.
824 .. [#] GeoDjango basic apps was written by Dane Springmeyer, Josh Livni, and
825 Christopher Schmidt.
826 .. [#] This point is the `University of Houston Law Center
827 <https://www.law.uh.edu/>`_.
828 .. [#] Open Geospatial Consortium, Inc., `OpenGIS Simple Feature Specification
829 For SQL <https://www.ogc.org/standards/sfs>`_.