---
title: "Ranganna Teagaisc GeodJango"
version: 6.1
locale: ga
source: https://docs.djangoproject.com/ga/6.1/ref/contrib/gis/tutorial/
canonical: https://djangodocs.dev/ga/6.1/ref/contrib/gis/tutorial/
---
# Ranganna Teagaisc GeodJango

## Réamhrá

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](https://www.ogc.org/) 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\>

> **Note**
>
> GeoDjango has additional requirements beyond what Django requires -- please
> consult the [installation documentation](/ga/6.1/ref/contrib/gis/install/) for more details.

Tabharfaidh an rang teagaisc seo treoir duit trí fheidhmchlár gréasáin geografach a chruthú chun féachaint ar na [teorainneacha domhain](https://code.google.com/archive/p/geodjango-basic-apps). \[#\] \_ 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](https://web.archive.org/web/20240123190237/https://thematicmapping.org/downloads/world_borders.php).

> **Note**
>
> Téigh ar aghaidh tríd na rannáin teagaisc go seicheamhach le haghaidh treoracha céim

## Ag bhunú

### Cruthaigh Bunachar Sonraí Spásúil

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

- [PostGIS a shuiteáil](/ga/6.1/ref/contrib/gis/install/postgis/)
- [Suiteáil SpatiaLite](/ga/6.1/ref/contrib/gis/install/spatialite/)

### Cruthaigh Tionscadal Nua

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

```console
$ django-admin startproject geodjango
```

*Windows*

```doscon
...\> django-admin startproject geodjango
```

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

```console
$ cd geodjango
$ python manage.py startapp world
```

*Windows*

```doscon
...\> cd geodjango
...\> py manage.py startapp world
```

### Cumraigh `settings.py`

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:

```
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):

```
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í Geografacha

### Teorainneacha Domhanda

The world borders data is available in this [zip file](https://web.archive.org/web/20231220150759/https://thematicmapping.org/downloads/TM_WORLD_BORDERS-0.3.zip). Create a `data`
directory in the `world` application, download the world borders data, and
unzip. On GNU/Linux platforms, use the following commands:

```console
$ 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*

```doscon
...\> 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](https://en.wikipedia.org/wiki/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ú

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

```console
$ 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*

```doscon
...\> 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:

```console
$ 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*

```doscon
...\> 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 Geografacha

### Samhail Geografach a shainiú

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ú:

```
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](https://en.wikipedia.org/wiki/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 `` `imirce ``

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í:

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

*Windows*

```doscon
...\> 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\`:

```console
$ python manage.py sqlmigrate world 0001
```

*Windows*

```doscon
...\> 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í:

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

*Windows*

```doscon
...\> 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 Iom

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](/ga/6.1/ref/contrib/gis/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](https://gdal.org/programs/ogr2ogr.html): 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](https://postgis.net/docs/using_postgis_dbmanagement.html#shp2pgsql_usage): An fóntais seo san áireamh le PostGIS allmhairíonn comhaid cruth ESRI isteach i PostGIS.

### Comhéadan GDAL

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:

```console
$ python manage.py shell
```

*Windows*

```doscon
...\> 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:

```pycon
>>> 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:

```pycon
>>> 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:

```pycon
>>> 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:

```pycon
>>> print(lyr.geom_type)
Polygon
>>> print(len(lyr))
246
```

> **Note**
>
> Unfortunately, the shapefile data format does not allow for greater
> specificity with regards to geometry types. This shapefile, like many
> others, actually includes `MultiPolygon` geometries, not Polygons. It's
> important to use a more general field type in models: a GeoDjango
> `MultiPolygonField` will accept a `Polygon` geometry, but a
> `PolygonField` will not accept a `MultiPolygon` type geometry. This is
> why the `WorldBorder` model defined above uses a `MultiPolygonField`.

The [`Layer`](/ga/6.1/ref/contrib/gis/gdal/#django.contrib.gis.gdal.Layer) may also have a spatial reference
system associated with it. If it does, the `srs` attribute will return a
[`SpatialReference`](/ga/6.1/ref/contrib/gis/gdal/#django.contrib.gis.gdal.SpatialReference) object:

```pycon
>>> 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:

```pycon
>>> 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í:

```pycon
>>> [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 () ):

```pycon
>>> 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`](/ga/6.1/ref/contrib/gis/gdal/#django.contrib.gis.gdal.Layer) objects may be sliced:

```pycon
>>> 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é:

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

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

```pycon
>>> 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 maping`

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:

```
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`:

```console
$ python manage.py shell
```

*Windows*

```doscon
...\> 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:

```pycon
>>> from world import load
>>> load.run()
```

### Bain triail as `ogrinspect`

Now that you've seen how to define geographic models and import data with the
[Fóntais allmhairithe sonraí Layermapping](/ga/6.1/ref/contrib/gis/layermapping/), it's possible to further automate this
process with use of the [`ogrinspect`](/ga/6.1/ref/contrib/gis/commands/#django-admin-ogrinspect) management command. The
[`ogrinspect`](/ga/6.1/ref/contrib/gis/commands/#django-admin-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:

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

*Windows*

```doscon
...\> 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:

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

*Windows*

```doscon
...\> 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:

```
# 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úla

### Cuardaigh Spásúla

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:

```console
$ python manage.py shell
```

*Windows*

```doscon
...\> py manage.py shell
```

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

```pycon
>>> 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:

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

Here, you retrieved a `QuerySet` with only one model instance: the border of
the United States (exactly what you would expect).

Similarly, you may also use a [GEOS geometry object](/ga/6.1/ref/contrib/gis/geos/). 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:

```pycon
>>> 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](/ga/6.1/ref/contrib/gis/db-api/) documentation has more.

### Claochluithe Spásúla

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](https://spatialreference.org/ref/epsg/32140/),
a coordinate system specific to south Texas **only** and in units of
**meters**, not degrees:

```pycon
>>> 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:

```pycon
>>> 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:

```pycon
>>> 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>]>
```

> **Fiosrúcháin amh**
>
> Agus tú ag úsáid: doc: fiosrúcháin am, ní mór duit do réimsí geoiméadrachta a fhilleadh ionas gur féidir le GEOS an luach réimse a ai\</topics/db/sql\> thint:
>
> ```pycon
> >>> from django.db import connection
> >>> # or if you're querying a non-default database:
> >>> from django.db import connections
> >>> connection = connections["your_gis_db_alias"]
> >>> City.objects.raw(
> ...     "SELECT id, name, %s as point from myapp_city" % (connection.ops.select % "point")
> ... )
> ```
>
> Níor chóir duit ceisteanna amh a úsáid ach nuair a bhíonn a fhios agat go díreach cad atá á dhéanamh agat.

### Geoiméadraí leisciúla

GeoDjango loads geometries in a standardized textual representation. When the
geometry field is first accessed, GeoDjango creates a
[`GEOSGeometry`](/ga/6.1/ref/contrib/gis/geos/#django.contrib.gis.geos.GEOSGeometry) object, exposing powerful
functionality, such as serialization properties for popular geospatial
formats:

```pycon
>>> 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:

```pycon
>>> pnt = Point(12.4604, 43.9420)
>>> sm.mpoly.contains(pnt)
True
>>> pnt.contains(sm.mpoly)
False
```

### Anótaí geografacha

GeoDjango also offers a set of geographic annotations to compute distances and
several other operations (intersection, difference, etc.). See the
[Feidhmeanna Bunachar Sonraí](/ga/6.1/ref/contrib/gis/functions/) documentation.

## Cuir do chuid sonraí ar an léarscáil

### Riarachán Geografach

[Django's admin application](/ga/6.1/ref/contrib/admin/) supports editing
geometry fields.

#### Buneilimintí

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](https://openlayers.org/)).

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

```
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:

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

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

Cruthaigh úsáideoir riaracháin:

```console
$ python manage.py createsuperuser
```

*Windows*

```doscon
...\> py manage.py createsuperuser
```

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

```console
$ python manage.py runserver
```

*Windows*

```doscon
...\> 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.

#### `GisModelAdmin`

Leis an: class: ~django.contrib.gis.admin.gismodelAdmin, úsáideann GeoDjango ciseal [OpenStreetMap](https://www.openstreetmap.org/) 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](http://web.archive.org/web/20201024202709/https://earth-info.nga.mil/publications/vmap0.html) WMS atá óstáilte ag [OsGeo](https://www.osgeo.org/)).

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`:

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

**Fonótaí**

[^1]: Buíochas speisialta do Bjørn Sandvik de mastermaps.net\`\< <https://mastermaps.net/>\> \_ as an tacar sonraí seo a sholáthar agus a chothabháil.

[^2]: Scríobh Dane Springmeyer, Josh Livni, agus Christopher Schmidt aipeanna bunúsacha GeodJango.

[^3]: Is é an pointe seo . \< <https://www.law.uh.edu/>\>

[^4]: \< <https://www.ogc.org/standards/sfs>\>Open Geospatial Consortium, Inc., .
