Ranganna Teagaisc GeodJangoLink to this heading

RéamhráLink to this heading

Is modúl contrib san áireamh é GeodJango do Django a iompaíonn é ina creat gréasáin geografach den scoth. Déanann GeodJango iarracht é a dhéanamh chomh simplí agus is féidir feidhmchláir gréasáin geografacha a chruthú, cosúil le seirbhísí suíomh-bhunaithe. I measc a ghnéithe tá:

  • Réimsí samhail Django le haghaidh geoiméadraí OGC agus sonraí raster.

  • Síntí ar ORM Django chun sonraí spásúla a cheistiú agus a ionramháil.

  • Comhéadain Python ardleibhéil, comhcheangailte go scaoilte le haghaidh geoiméadracht GIS agus oibríochtaí raster agus ionramháil sonraí i bhformáidí éag

  • Réimsí geoiméadra a chur in eagar ón riarachán

Glacann an rang teagaisc seo le eolas ar Django; dá bhrí sin, má tá tú nua-aimseartha do Django, léigh trí:doc: `rang teagaisc rialta' le do thoil chun eolas a chur ar Django ar dtús. </intro/tutorial01>

Tabharfaidh an rang teagaisc seo treoir duit trí fheidhmchlár gréasáin geografach a chruthú chun féachaint ar na teorainneacha domhain. [#] _ Tógtar cuid den chód a úsáidtear sa rang teagaisc seo ó thionscadal GeoDjango bunaipeanna `_ agus/nó spreagtha ag an tionscadal `GeoDjango bunús.

Ag bhunúLink to this heading

Cruthaigh Bunachar Sonraí SpásúilLink to this heading

De ghnáth ní theastaíonn socrú speisialta, ionas gur féidir leat bunachar sonraí a chruthú mar a dhéanfá d'aon tionscadal eile. Soláthraímid roinnt leideanna do bhunachar sonraí roghnai

Cruthaigh Tionscadal NuaLink to this heading

Úsáid an script caighdeánach django-admin ``chun tionscadal ar a dtugtar ``geodjango a chruthú:

Linux / macOS

Shell
$ django-admin startproject geodjango

Windows

Windows
...\> django-admin startproject geodjango

Cuirfidh sé seo tionscadal nua a thosú. Anois, cruthaigh feidhmchlár domh Django laistigh den tionscadal geodjango:

Linux / macOS

Shell
$ cd geodjango
$ python manage.py startapp world

Windows

Windows
...\> cd geodjango
...\> py manage.py startapp world

Cumraigh settings.pyLink to this heading

Stóráiltear na socruithe tionscadail geodjango sa chomhad geodjango/settings.py. Cuir na socruithe nasc bunachar sonraí in eagar chun do shocrú a mheaitseáil:

Code
DATABASES = {
    "default": {
        "ENGINE": "django.contrib.gis.db.backends.postgis",
        "NAME": "geodjango",
        "USER": "geo",
    },
}

Ina theannta sin, modhnaigh an socrú:setting: INSTALLED_APPS chun go n-áirítear: mod: django.contrib.admin, :mod: django.contrib.gis, agus world (d'iarratas nua-chruthaithe):

Code
INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "django.contrib.gis",
    "world",
]

Sonraí GeografachaLink to this heading

Teorainneacha DomhandaLink to this heading

The world borders data is available in this zip file. Create a data directory in the world application, download the world borders data, and unzip. On GNU/Linux platforms, use the following commands:

Linux / macOS

Shell
$ mkdir world/data
$ cd world/data
$ wget https://web.archive.org/web/20231220150759/https://thematicmapping.org/downloads/TM_WORLD_BORDERS-0.3.zip
$ unzip TM_WORLD_BORDERS-0.3.zip
$ cd ../..

Windows

Windows
...\> mkdir world\data
...\> cd world\data
...\> wget https://web.archive.org/web/20231220150759/https://thematicmapping.org/downloads/TM_WORLD_BORDERS-0.3.zip
...\> unzip TM_WORLD_BORDERS-0.3.zip
...\> cd ..\..

The world borders ZIP file contains a set of data files collectively known as an ESRI Shapefile, one of the most popular geospatial data formats. When unzipped, the world borders dataset includes files with the following extensions:

  • .shp: Coinníonn na sonraí veicteora do gheoiméadrachtaí teorainneacha domhanda.

  • .shx: Comhad innéacs spásúil le haghaidh geoiméadraí atá stóráilte sa .shp`.

  • .dbf: Comhad bunachar sonraí chun sonraí tréithe neamh-geoiméadracha a choinneáil (m.sh., réimsí sláimhir agus carachtar).

  • .prj: Tá an fhaisnéis tagartha spásúil ann do na sonraí geografacha atá stóráilte sa chomhad cruth.

Úsáid ogrinfo chun sonraí spásúla a scrúdúLink to this heading

Ligeann fóntais GDAL ``ogrinfo` a scrúdú ar mheiteashonraí comhaid cruth nó foinsí sonraí veicteora eile:

Linux / macOS

Shell
$ ogrinfo world/data/TM_WORLD_BORDERS-0.3.shp
INFO: Open of `world/data/TM_WORLD_BORDERS-0.3.shp'
      using driver `ESRI Shapefile' successful.
1: TM_WORLD_BORDERS-0.3 (Polygon)

Windows

Windows
...\> ogrinfo world\data\TM_WORLD_BORDERS-0.3.shp
INFO: Open of `world/data/TM_WORLD_BORDERS-0.3.shp'
      using driver `ESRI Shapefile' successful.
1: TM_WORLD_BORDERS-0.3 (Polygon)

ogrinfo tells us that the shapefile has one layer, and that this layer contains polygon data. To find out more, we'll specify the layer name and use the -so option to get only the important summary information:

Linux / macOS

Shell
$ ogrinfo -so world/data/TM_WORLD_BORDERS-0.3.shp TM_WORLD_BORDERS-0.3
INFO: Open of `world/data/TM_WORLD_BORDERS-0.3.shp'
      using driver `ESRI Shapefile' successful.

Layer name: TM_WORLD_BORDERS-0.3
Metadata:
  DBF_DATE_LAST_UPDATE=2008-07-30
Geometry: Polygon
Feature Count: 246
Extent: (-180.000000, -90.000000) - (180.000000, 83.623596)
Layer SRS WKT:
GEOGCRS["WGS 84",
    DATUM["World Geodetic System 1984",
        ELLIPSOID["WGS 84",6378137,298.257223563,
            LENGTHUNIT["metre",1]]],
    PRIMEM["Greenwich",0,
        ANGLEUNIT["degree",0.0174532925199433]],
    CS[ellipsoidal,2],
        AXIS["latitude",north,
            ORDER[1],
            ANGLEUNIT["degree",0.0174532925199433]],
        AXIS["longitude",east,
            ORDER[2],
            ANGLEUNIT["degree",0.0174532925199433]],
    ID["EPSG",4326]]
Data axis to CRS axis mapping: 2,1
FIPS: String (2.0)
ISO2: String (2.0)
ISO3: String (3.0)
UN: Integer (3.0)
NAME: String (50.0)
AREA: Integer (7.0)
POP2005: Integer64 (10.0)
REGION: Integer (3.0)
SUBREGION: Integer (3.0)
LON: Real (8.3)
LAT: Real (7.3)

Windows

Windows
...\> ogrinfo -so world\data\TM_WORLD_BORDERS-0.3.shp TM_WORLD_BORDERS-0.3
INFO: Open of `world/data/TM_WORLD_BORDERS-0.3.shp'
      using driver `ESRI Shapefile' successful.

Layer name: TM_WORLD_BORDERS-0.3
Metadata:
  DBF_DATE_LAST_UPDATE=2008-07-30
Geometry: Polygon
Feature Count: 246
Extent: (-180.000000, -90.000000) - (180.000000, 83.623596)
Layer SRS WKT:
GEOGCRS["WGS 84",
    DATUM["World Geodetic System 1984",
        ELLIPSOID["WGS 84",6378137,298.257223563,
            LENGTHUNIT["metre",1]]],
    PRIMEM["Greenwich",0,
        ANGLEUNIT["degree",0.0174532925199433]],
    CS[ellipsoidal,2],
        AXIS["latitude",north,
            ORDER[1],
            ANGLEUNIT["degree",0.0174532925199433]],
        AXIS["longitude",east,
            ORDER[2],
            ANGLEUNIT["degree",0.0174532925199433]],
    ID["EPSG",4326]]
Data axis to CRS axis mapping: 2,1
FIPS: String (2.0)
ISO2: String (2.0)
ISO3: String (3.0)
UN: Integer (3.0)
NAME: String (50.0)
AREA: Integer (7.0)
POP2005: Integer64 (10.0)
REGION: Integer (3.0)
SUBREGION: Integer (3.0)
LON: Real (8.3)
LAT: Real (7.3)

This detailed summary information tells us the number of features in the layer (246), the geographic bounds of the data, the spatial reference system ("SRS WKT"), as well as type information for each attribute field. For example, FIPS: String (2.0) indicates that the FIPS character field has a maximum length of 2. Similarly, LON: Real (8.3) is a floating-point field that holds a maximum of 8 digits up to three decimal places.

Samhlacha GeografachaLink to this heading

Samhail Geografach a shainiúLink to this heading

Anois go ndearna tú scrúdú ar do thacar sonraí ag baint úsáide as ``ogrinfo`, cruthaigh samhail GeodJango chun na sonraí seo a léiriú:

Code
from django.contrib.gis.db import models


class WorldBorder(models.Model):
    # Regular Django fields corresponding to the attributes in the
    # world borders shapefile.
    name = models.CharField(max_length=50)
    area = models.IntegerField()
    pop2005 = models.IntegerField("Population 2005")
    fips = models.CharField("FIPS Code", max_length=2, null=True)
    iso2 = models.CharField("2 Digit ISO", max_length=2)
    iso3 = models.CharField("3 Digit ISO", max_length=3)
    un = models.IntegerField("United Nations Code")
    region = models.IntegerField("Region Code")
    subregion = models.IntegerField("Sub-Region Code")
    lon = models.FloatField()
    lat = models.FloatField()

    # GeoDjango-specific: a geometry field (MultiPolygonField)
    mpoly = models.MultiPolygonField()

    # Returns the string representation of the model.
    def __str__(self):
        return self.name

Tabhair faoi deara go n-allmhairítear an modúl samhlacha ``ó `django.contrib.gis.db.

The default spatial reference system for geometry fields is WGS84 (meaning the SRID is 4326) -- in other words, the field coordinates are in longitude, latitude pairs in units of degrees. To use a different coordinate system, set the SRID of the geometry field with the srid argument. Use an integer representing the coordinate system's EPSG code.

Rith `imirceLink to this heading

Tar éis duit do mhúnla a shainiú, ní mór duit é a shioncronú leis an mbunachar sonraí. Ar dtús, cruthaigh imirce bunachar sonraí:

Linux / macOS

Shell
$ python manage.py makemigrations
Migrations for 'world':
  world/migrations/0001_initial.py:
    + Create model WorldBorder

Windows

Windows
...\> py manage.py makemigrations
Migrations for 'world':
  world/migrations/0001_initial.py:
    + Create model WorldBorder

Breathnaímid ar an SQL a ghinfidh an tábla don tsamhail ``Worldborder`:

Linux / macOS

Shell
$ python manage.py sqlmigrate world 0001

Windows

Windows
...\> py manage.py sqlmigrate world 0001

Ba chóir go dtáirgfeadh an t-ordú seo an t-aschur seo

SQL
BEGIN;
--
-- Create model WorldBorder
--
CREATE TABLE "world_worldborder" (
    "id" bigint NOT NULL PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
    "name" varchar(50) NOT NULL,
    "area" integer NOT NULL,
    "pop2005" integer NOT NULL,
    "fips" varchar(2) NOT NULL,
    "iso2" varchar(2) NOT NULL,
    "iso3" varchar(3) NOT NULL,
    "un" integer NOT NULL,
    "region" integer NOT NULL,
    "subregion" integer NOT NULL,
    "lon" double precision NOT NULL,
    "lat" double precision NOT NULL
    "mpoly" geometry(MULTIPOLYGON,4326) NOT NULL
)
;
CREATE INDEX "world_worldborder_mpoly_id" ON "world_worldborder" USING GIST ("mpoly");
COMMIT;

Má tá cuma ceart air seo, rith: djadmin: migrate chun an tábla seo a chruthú sa bhunachar sonraí:

Linux / macOS

Shell
$ python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions, world
Running migrations:
  ...
  Applying world.0001_initial... OK

Windows

Windows
...\> py manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions, world
Running migrations:
  ...
  Applying world.0001_initial... OK

Sonraí Spásúla a IomLink to this heading

This section will show you how to import the world borders shapefile into the database via GeoDjango models using the Fóntais allmhairithe sonraí Layermapping.

Tá go leor bealaí éagsúla ann chun sonraí a iompórtáil isteach i mbunachar sonraí spásúil - seachas na huirlisí atá san áireamh laistigh de GeodJango, is féidir leat na rudaí seo a leanas a úsáid

  • ogr2ogr: Fóntais líne ordaithe san áireamh le GDAL atá in ann go leor formáidí sonraí veicteora a iompórtáil isteach i mbunachair sonraí PostGIS, MySQL, agus Oracle.

  • shp2pgsql: An fóntais seo san áireamh le PostGIS allmhairíonn comhaid cruth ESRI isteach i PostGIS.

Comhéadan GDALLink to this heading

Earlier, you used ogrinfo to examine the contents of the world borders shapefile. GeoDjango also includes a Pythonic interface to GDAL's powerful OGR library that can work with all the vector data sources that OGR supports.

Ar dtús, glaoch ar an bhlaosc Django:

Linux / macOS

Shell
$ python manage.py shell

Windows

Windows
...\> py manage.py shell

Má íoslódáil tú na sonraí:ref: worldborders níos luaithe sa rang teagaisc, ansin is féidir leat a chonair a chinneadh ag baint úsáide as Python's:class: pathlib.path:

Python console
>>> from pathlib import Path
>>> import world
>>> world_shp = Path(world.__file__).resolve().parent / "data" / "TM_WORLD_BORDERS-0.3.shp"

Anois, oscail an comhad cruth teorainneacha domhanda ag baint úsáide as comhéadan GeodjangoS:Class: ~django.contrib.gis.gdal.datasource:

Python console
>>> from django.contrib.gis.gdal import DataSource
>>> ds = DataSource(world_shp)
>>> print(ds)
/ ... /geodjango/world/data/TM_WORLD_BORDERS-0.3.shp (ESRI Shapefile)

Is féidir le sraitheanna éagsúla de ghnéithe geospásúla a bheith ag rudaí foinse sonraí; áfach, ní cheadaítear ach sraith amháin a bheith ag comhaid chruthacha:

Python console
>>> print(len(ds))
1
>>> lyr = ds[0]
>>> print(lyr)
TM_WORLD_BORDERS-0.3

Is féidir leat cineál geoiméadrach an chiseal a fheiceáil agus cé mhéad gné atá ann:

Python console
>>> print(lyr.geom_type)
Polygon
>>> print(len(lyr))
246

The Layer may also have a spatial reference system associated with it. If it does, the srs attribute will return a SpatialReference object:

Python console
>>> srs = lyr.srs
>>> print(srs)
GEOGCS["WGS 84",
DATUM["WGS_1984",
    SPHEROID["WGS 84",6378137,298.257223563,
        AUTHORITY["EPSG","7030"]],
    AUTHORITY["EPSG","6326"]],
PRIMEM["Greenwich",0,
    AUTHORITY["EPSG","8901"]],
UNIT["degree",0.0174532925199433,
    AUTHORITY["EPSG","9122"]],
AXIS["Latitude",NORTH],
AXIS["Longitude",EAST],
AUTHORITY["EPSG","4326"]]
>>> srs.proj  # PROJ representation
'+proj=longlat +datum=WGS84 +no_defs'

Tá an comhad cruth seo sa chóras tagartha spásúil WGS84 a bhfuil tóir orthu - is é sin le rá, úsáideann na sonraí domhanfhad, péirí domhanleithead in aonaid céimeanna.

In addition, shapefiles also support attribute fields that may contain additional data. Here are the fields on the World Borders layer:

Python console
>>> print(lyr.fields)
['FIPS', 'ISO2', 'ISO3', 'UN', 'NAME', 'AREA', 'POP2005', 'REGION', 'SUBREGION', 'LON', 'LAT']

Ligfidh an cód seo a leanas duit scrúdú a dhéanamh ar na cineálacha OGR (m.shláimhir nó sreang) a bhaineann le gach ceann de na réimsí:

Python console
>>> [fld.__name__ for fld in lyr.field_types]
['OFTString', 'OFTString', 'OFTString', 'OFTInteger', 'OFTString', 'OFTInteger', 'OFTInteger64', 'OFTInteger', 'OFTInteger', 'OFTReal', 'OFTReal']

Is féidir leat athrá thar gach gné sa chiseal agus faisnéis a bhaint as geoiméadacht na gné (rochtain tríd an tréith geom) chomh maith le réimsí tréithe na ngné (a gcuirtear rochtain ar a luacha** trí mhodh ``get () ``):

Python console
>>> for feat in lyr:
...     print(feat.get("NAME"), feat.geom.num_points)
...
Guernsey 18
Jersey 26
South Georgia South Sandwich Islands 338
Taiwan 363

Layer objects may be sliced:

Python console
>>> lyr[0:2]
[<django.contrib.gis.gdal.feature.Feature object at 0x2f47690>, <django.contrib.gis.gdal.feature.Feature object at 0x2f47650>]

Agus is féidir gnéithe aonair a aisghabháil ag a n-ID gné:

Python console
>>> feat = lyr[234]
>>> print(feat.get("NAME"))
San Marino

Féadfar geoiméadraí teorann a onnmhairiú mar WKT agus GeoJSON:

Python console
>>> geom = feat.geom
>>> print(geom.wkt)
POLYGON ((12.415798 43.957954,12.450554 ...
>>> print(geom.json)
{ "type": "Polygon", "coordinates": [ [ [ 12.415798, 43.957954 ], [ 12.450554, 43.979721 ], ...

Sraith mapingLink to this heading

Chun na sonraí a iompórtáil, bain úsáid as LayerMapping i script Python. Cruthaigh comhad ar a dtugtar load.py taobh istigh den fheidhmchlár world, leis an gcód seo a leanas:

Code
from pathlib import Path
from django.contrib.gis.utils import LayerMapping
from .models import WorldBorder

world_mapping = {
    "fips": "FIPS",
    "iso2": "ISO2",
    "iso3": "ISO3",
    "un": "UN",
    "name": "NAME",
    "area": "AREA",
    "pop2005": "POP2005",
    "region": "REGION",
    "subregion": "SUBREGION",
    "lon": "LON",
    "lat": "LAT",
    "mpoly": "MULTIPOLYGON",
}

world_shp = Path(__file__).resolve().parent / "data" / "TM_WORLD_BORDERS-0.3.shp"


def run(verbose=True):
    lm = LayerMapping(WorldBorder, world_shp, world_mapping, transform=False)
    lm.save(strict=True, verbose=verbose)

Cúpla nóta faoin méid atá ar siúl:

  • Each key in the world_mapping dictionary corresponds to a field in the WorldBorder model. The value is the name of the shapefile field that data will be loaded from.

  • The key mpoly for the geometry field is MULTIPOLYGON, the geometry type GeoDjango will import the field as. Even simple polygons in the shapefile will automatically be converted into collections prior to insertion into the database.

  • Níl an cosán chuig an bhformáid iomlán - is é sin le rá, má bhogann tú an feidhmchlár ``domhan` (le fo-eolaire ``sonraí ``) go suíomh difriúil, oibreoidh an script fós.

  • Tá an eochairfhocal transform` socraithe go ``False toisc nach gá na sonraí sa chomhad cruth a thiontú - tá sé i WGS84 cheana féin (SRID = 4326).

Ina dhiaidh sin, glaoch ar an bhlaosc Django ón eolaire tionscadail geodjango:

Linux / macOS

Shell
$ python manage.py shell

Windows

Windows
...\> py manage.py shell

Ansin, iompórtáil an modúl load ``, glaoigh ar an ngnáthamh ``run, agus féach ar Layermapping ag déanamh an obair:

Python console
>>> from world import load
>>> load.run()

Bain triail as ogrinspectLink to this heading

Now that you've seen how to define geographic models and import data with the Fóntais allmhairithe sonraí Layermapping, it's possible to further automate this process with use of the ogrinspect management command. The ogrinspect command introspects a GDAL-supported vector data source (e.g., a shapefile) and generates a model definition and LayerMapping dictionary automatically.

Tá úsáid ghinearálta an ordaithe mar seo a leanas:

Linux / macOS

Shell
$ python manage.py ogrinspect [options] <data_source> <model_name> [options]

Windows

Windows
...\> py manage.py ogrinspect [options] <data_source> <model_name> [options]

data_source is the path to the GDAL-supported data source and model_name is the name to use for the model. Command-line options may be used to further define how the model is generated.

Mar shampla, atháirgeann an t-ordú seo a leanas beagnach an tsamhail Worldborder agus an foclóir mapála a cruthaíodh thuas, go huathoibríoch:

Linux / macOS

Shell
$ python manage.py ogrinspect world/data/TM_WORLD_BORDERS-0.3.shp WorldBorder \
    --srid=4326 --mapping --multi

Windows

Windows
...\> py manage.py ogrinspect world\data\TM_WORLD_BORDERS-0.3.shp WorldBorder \
    --srid=4326 --mapping --multi

Cúpla nóta faoi na roghanna líne ordaithe a thugtar thuas:

  • Socraíonn an rogha --srid = 4326 an SRID don réimse geografach.

  • Insíonn an rogha --mapping le ogrinspect foclóir mapála a ghiniúint freisin le húsáid le:class: ~django.contrib.gis.utils.layermapping.

  • Sonraítear an rogha --multi ionas gurb é an réimse geografach a:class: ~django.contrib.gis.db.models.multipolygonfield in ionad ach a:class: ~django.contrib.gis.db.models.polygonfield.

Táirgeann an t-ordú an t-aschur seo a leanas, ar féidir a chóipeáil go díreach isteach sa models.py` d'fheidhmchlár GeoDjango:

Code
# This is an auto-generated Django model module created by ogrinspect.
from django.contrib.gis.db import models


class WorldBorder(models.Model):
    fips = models.CharField(max_length=2)
    iso2 = models.CharField(max_length=2)
    iso3 = models.CharField(max_length=3)
    un = models.IntegerField()
    name = models.CharField(max_length=50)
    area = models.IntegerField()
    pop2005 = models.IntegerField()
    region = models.IntegerField()
    subregion = models.IntegerField()
    lon = models.FloatField()
    lat = models.FloatField()
    geom = models.MultiPolygonField(srid=4326)


# Auto-generated `LayerMapping` dictionary for WorldBorder model
worldborders_mapping = {
    "fips": "FIPS",
    "iso2": "ISO2",
    "iso3": "ISO3",
    "un": "UN",
    "name": "NAME",
    "area": "AREA",
    "pop2005": "POP2005",
    "region": "REGION",
    "subregion": "SUBREGION",
    "lon": "LON",
    "lat": "LAT",
    "geom": "MULTIPOLYGON",
}

Ceisteanna SpásúlaLink to this heading

Cuardaigh SpásúlaLink to this heading

GeoDjango adds spatial lookups to the Django ORM. For example, you can find the country in the WorldBorder table that contains a particular point. First, fire up the management shell:

Linux / macOS

Shell
$ python manage.py shell

Windows

Windows
...\> py manage.py shell

Anois, sainmhínigh pointe spéise [#] _:

Python console
>>> pnt_wkt = "POINT(-95.3385 29.7245)"

The pnt_wkt string represents the point at -95.3385 degrees longitude, 29.7245 degrees latitude. The geometry is in a format known as Well Known Text (WKT), a standard issued by the Open Geospatial Consortium (OGC). [4] Import the WorldBorder model, and perform a contains lookup using the pnt_wkt as the parameter:

Python console
>>> from world.models import WorldBorder
>>> WorldBorder.objects.filter(mpoly__contains=pnt_wkt)
<QuerySet [<WorldBorder: United States>]>

Anseo, ghnóthaigh tú ``QuerySet ``gan ach samhail amháin: teorainn na Stát Aontaithe (go díreach cad a bheadh ag súil leat).

Similarly, you may also use a GEOS geometry object. Here, you can combine the intersects spatial lookup with the get method to retrieve only the WorldBorder instance for San Marino instead of a queryset:

Python console
>>> from django.contrib.gis.geos import Point
>>> pnt = Point(12.4604, 43.9420)
>>> WorldBorder.objects.get(mpoly__intersects=pnt)
<WorldBorder: San Marino>

The contains and intersects lookups are just a subset of the available queries -- the API Bunachar Sonraí GeodJango documentation has more.

Claochluithe SpásúlaLink to this heading

When doing spatial queries, GeoDjango automatically transforms geometries if they're in a different coordinate system. In the following example, coordinates will be expressed in EPSG SRID 32140, a coordinate system specific to south Texas only and in units of meters, not degrees:

Python console
>>> from django.contrib.gis.geos import GEOSGeometry, Point
>>> pnt = Point(954158.1, 4215137.1, srid=32140)

Tabhair faoi deara gur féidir “pnt” a thógáil le EWKT freisin, foirm “leathnaithe” de WKT a chuimsíonn an SRID:

Python console
>>> pnt = GEOSGeometry("SRID=32140;POINT(954158.1 4215137.1)")

Fillfidh ORM GeodJango luachanna geoiméadrachta go huathoibríoch i SQL claochlú, rud a ligeann don fhorbróir oibriú ag leibhéal níos airde teastartha:

Python console
>>> qs = WorldBorder.objects.filter(mpoly__intersects=pnt)
>>> print(qs.query)  # Generating the SQL
SELECT "world_worldborder"."id", "world_worldborder"."name", "world_worldborder"."area",
"world_worldborder"."pop2005", "world_worldborder"."fips", "world_worldborder"."iso2",
"world_worldborder"."iso3", "world_worldborder"."un", "world_worldborder"."region",
"world_worldborder"."subregion", "world_worldborder"."lon", "world_worldborder"."lat",
"world_worldborder"."mpoly" FROM "world_worldborder"
WHERE ST_Intersects("world_worldborder"."mpoly", ST_Transform(%s, 4326))
>>> qs  # printing evaluates the queryset
<QuerySet [<WorldBorder: United States>]>

Geoiméadraí leisciúlaLink to this heading

GeoDjango loads geometries in a standardized textual representation. When the geometry field is first accessed, GeoDjango creates a GEOSGeometry object, exposing powerful functionality, such as serialization properties for popular geospatial formats:

Python console
>>> sm = WorldBorder.objects.get(name="San Marino")
>>> sm.mpoly
<MultiPolygon object at 0x24c6798>
>>> sm.mpoly.wkt  # WKT
MULTIPOLYGON (((12.4157980000000006 43.9579540000000009, 12.4505540000000003 43.9797209999999978, ...
>>> sm.mpoly.wkb  # WKB (as Python binary buffer)
<read-only buffer for 0x1fe2c70, size -1, offset 0 at 0x2564c40>
>>> sm.mpoly.geojson  # GeoJSON
'{ "type": "MultiPolygon", "coordinates": [ [ [ [ 12.415798, 43.957954 ], [ 12.450554, 43.979721 ], ...

Áirítear leis seo rochtain ar na hardoibríochtaí geoiméadracha go léir a sholáthraíonn leabharlann GEOS:

Python console
>>> pnt = Point(12.4604, 43.9420)
>>> sm.mpoly.contains(pnt)
True
>>> pnt.contains(sm.mpoly)
False

Anótaí geografachaLink to this heading

GeoDjango also offers a set of geographic annotations to compute distances and several other operations (intersection, difference, etc.). See the Feidhmeanna Bunachar Sonraí documentation.

Cuir do chuid sonraí ar an léarscáilLink to this heading

Riarachán GeografachLink to this heading

Django's admin application supports editing geometry fields.

BuneilimintíLink to this heading

Ligeann riarachán Django d'úsáideoirí geoiméadraí a chruthú agus a mhodhnú ar léarscáil slippy JavaScript (faoi thiomáint ag OpenLayers).

Déanaimis tumadóireacht isteach. Cruthaigh comhad darb ainm admin.py` taobh istigh den fheidhmchlár domh leis an gcód seo a leanas:

Code
from django.contrib.gis import admin
from .models import WorldBorder

admin.site.register(WorldBorder, admin.ModelAdmin)

Ansin, cuir do urls.py` in eagar san fhillteán feidhmchláir geodjango mar seo a leanas:

Code
from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path("admin/", admin.site.urls),
]

Cruthaigh úsáideoir riaracháin:

Linux / macOS

Shell
$ python manage.py createsuperuser

Windows

Windows
...\> py manage.py createsuperuser

Ansin, cuir tús leis an bhfreastalaí forbartha Django:

Linux / macOS

Shell
$ python manage.py runserver

Windows

Windows
...\> py manage.py runserver

Faoi dheireadh, brabhsáil chuig http://localhost:8000/admin/, agus logáil isteach leis an úsáideoir a chruthaigh tú díreach. Brabhsáil chuig aon cheann de na hiontrálacha Worldborder - is féidir na teorainneacha a chur in eagar trí chliceáil ar pholugún agus na coirteanna a tharraingt go dtí an suíomh atá ag teastáil.

GisModelAdminLink to this heading

Leis an: class: ~django.contrib.gis.admin.gismodelAdmin, úsáideann GeoDjango ciseal OpenStreetMap sa riarachán. Soláthraíonn sé seo níos mó comhthéacs (lena n-áirítear sonraí sráide agus smachta) ná mar atá ar fáil len:class: ~django.contrib.admin.modelAdmin (a úsáideann an tacar sonraí Level Léarscáil Vector 0 WMS atá óstáilte ag OsGeo).

Caithfear na comhaid aistrithe dáta PROJ a shuiteáil (féach an:ref: `Treoracha suiteála PROJ <proj4>`le haghaidh tuilleadh sonraí).

Má chomhlíonann tú an riachtanas seo, ansin bain úsáid as an rang rogha GisModelAdmin i do chomhad admin.py:

Code
admin.site.register(WorldBorder, admin.GISModelAdmin)

Fonótaí