# Dokumentasi Django 6.0.7

# API Basisdata GeoDjango

## Backend Spasial

GeoDjango saat ini menyediakan backend basisdata spasial berikut:

- django.contrib.gis.db.backends.postgis`

- `django.contrib.gis.db.backends.mysql`

- `django.contrib.gis.db.backends.oracle`

- `django.contrib.gis.db.backends.spatialite`

### Batasan Spasial MySQL

Django supports spatial functions operating on real geometries available in modern MySQL versions. However, the spatial functions are not as rich as other backends like PostGIS.

### Dukungan Raster

`RasterField` saat ini hanya diterapkan untuk backend PostGIS. Pencarian spasial tersedia untuk bidang raster, tetapi fungsi basisdata spasial dan pengumpulan tidak diterapkan untuk bidang taster.

## Membuat dan Menyimpan Model dengan Bidang Geometri

Here is an example of how to create a geometry object (assuming the `Zipcode` model):

    >>> from zipcode.models import Zipcode
    >>> z = Zipcode(code=77096, poly="POLYGON(( 10 10, 10 20, 20 20, 20 15, 10 10))")
    >>> z.save()

`GEOSGeometry` objects may also be used to save geometric models:

    >>> from django.contrib.gis.geos import GEOSGeometry
    >>> poly = GEOSGeometry("POLYGON(( 10 10, 10 20, 20 20, 20 15, 10 10))")
    >>> z = Zipcode(code=77096, poly=poly)
    >>> z.save()

Moreover, if the `GEOSGeometry` is in a different coordinate system (has a different SRID value) than that of the field, then it will be implicitly transformed into the SRID of the model's field, using the spatial database's transform procedure:

    >>> poly_3084 = GEOSGeometry(
    ...     "POLYGON(( 10 10, 10 20, 20 20, 20 15, 10 10))", srid=3084
    ... )  # SRID 3084 is 'NAD83(HARN) / Texas Centric Lambert Conformal'
    >>> z = Zipcode(code=78212, poly=poly_3084)
    >>> z.save()
    >>> from django.db import connection
    >>> print(
    ...     connection.queries[-1]["sql"]
    ... )  # printing the last SQL statement executed (requires DEBUG=True)
    INSERT INTO "geoapp_zipcode" ("code", "poly") VALUES (78212, ST_Transform(ST_GeomFromWKB('\\001 ... ', 3084), 4326))

Thus, geometry parameters may be passed in using the `GEOSGeometry` object, WKT (Well Known Text [1]), HEXEWKB (PostGIS specific -- a WKB geometry in hexadecimal [2]), and GeoJSON (see RFC 7946). Essentially, if the input is not a `GEOSGeometry` object, the geometry field will attempt to create a `GEOSGeometry` instance from the input.

Untuk informasi lebih membuat obyek `GEOSGeometry` mengacu pada GEOS tutorial 1.

## Membuat dan Menyimpan Model dengan Bidang Raster

Ketika membuat model raster, bidang raster akan secara jelas merubah masukan kedalam `GDALRaster`.

Here is an example of how to create a raster object from a raster file `volcano.tif` (assuming the `Elevation` model):

    >>> from elevation.models import Elevation
    >>> dem = Elevation(name="Volcano", rast="/path/to/raster/volcano.tif")
    >>> dem.save()

`GDALRaster` objects may also be used to save raster models:

    >>> from django.contrib.gis.gdal import GDALRaster
    >>> rast = GDALRaster(
    ...     {
    ...         "width": 10,
    ...         "height": 10,
    ...         "name": "Canyon",
    ...         "srid": 4326,
    ...         "scale": [0.1, -0.1],
    ...         "bands": [{"data": range(100)}],
    ...     }
    ... )
    >>> dem = Elevation(name="Canyon", rast=rast)
    >>> dem.save()

Note that this is equivalent to:

    >>> dem = Elevation.objects.create(
    ...     name="Canyon",
    ...     rast={
    ...         "width": 10,
    ...         "height": 10,
    ...         "name": "Canyon",
    ...         "srid": 4326,
    ...         "scale": [0.1, -0.1],
    ...         "bands": [{"data": range(100)}],
    ...     },
    ... )

## Pencarian Spasial

GeoDjango's lookup types may be used with any manager method like `filter()`, `exclude()`, etc. However, the lookup types unique to GeoDjango are only available on spatial fields.

Filters on 'normal' fields (e.g. `CharField`) may be chained with those on geographic fields. Geographic lookups accept geometry and raster input on both sides, and input types can be mixed freely in most cases. However, unlike assignments to model fields, with lookups, types such as `str`, `pathlib.Path`, and `dict` must be wrapped by `GDALRaster` to signify that the potential for file writing or network fetching is acceptable. For the rationale, see raster security considerations.

Struktur umum dari pencarian geografis akan digambarkan dibawah ini. Acuan lengkap dapat ditemukan dalam spatial lookup reference1.

Changed in Django 5.2.17:

In earlier versions, spatial lookups accepted `str` and `dict` types for new rasters, allowing file writes and network fetches.

### Pencarian Geometri

Geographic queries with geometries take the following general form (assuming the `Zipcode` model used in the API Model GeoDjango):

    >>> qs = Zipcode.objects.filter(<field>__<lookup_type>=<parameter>)
    >>> qs = Zipcode.objects.exclude(...)

Sebagai contoh:

    >>> qs = Zipcode.objects.filter(poly__contains=pnt)
    >>> qs = Elevation.objects.filter(poly__contains=rst)

Dalam kasus ini, `poly` adalah bidang geofgrafis, `contains 1` adalah jenis pencarian spasial, `pnt` adalah parameter (yang mungkin berupa obyek `GEOSGeometry` atau string dari GeoJSON , WKT, atau HEXEWKB), dan `rst` adalah sebuah obyek `GDALRaster`.

### Pencarian Raster

Sintaksis pencarian raster mitip pada sintaksis untuk geometri. Perbedaan hanya bahwa peta indesk dapat ditentukan sebagai input tambahan. Jika tidak ada pita indeks ditentukan, pita pertama digunakan secara awalan (indeks `0`). Dalam kasus itu sintaksis mirip ke sintaksis untuk pencarian geometri.

Untuk menentukan pita indeks, sebuah parameter tambahan dapat ditentukan pada kedua sisi dari pencarian. Pada sisi tangan kiri, sintaksis garis bawah ganda digunakan peta indeks. Pada sisi tangan kanan, tuple dari raster dan pita indeks dapat ditentukan.

This results in the following general form for lookups involving rasters (assuming the `Elevation` model used in the API Model GeoDjango):

    >>> qs = Elevation.objects.filter(<field>__<lookup_type>=<parameter>)
    >>> qs = Elevation.objects.filter(<field>__<band_index>__<lookup_type>=<parameter>)
    >>> qs = Elevation.objects.filter(<field>__<lookup_type>=(<raster_input, <band_index>)

Sebagai contoh:

    >>> qs = Elevation.objects.filter(rast__contains=geom)
    >>> qs = Elevation.objects.filter(rast__contains=rst)
    >>> qs = Elevation.objects.filter(rast__1__contains=geom)
    >>> qs = Elevation.objects.filter(rast__contains=(rst, 1))
    >>> qs = Elevation.objects.filter(rast__1__contains=(rst, 1))

Pada sisi tangan kiri dari contoh, `rast` adalah bidang raster geografis dan `contains 1` adalah jenis pencarian spasial. Pada sisi tangan kanan, `geom` adalah masukan geometri dan `rst` adalah sebuah obyek `GDALRaster`. Pinta indeks awalan pada `0` dalam permintaan dua pertama dan disetel menjadi `1` pada lainnya.

Selagi semuan pencarian spasial dapat digunakan dengan obyek raster pada kedua sisi tidak semua penghubung pokok asli menerima masukan raster. Untuk kasus-kasus dimana penghubung mengharapkan masukan geometri, raster adalah secara otomatis dirubah kegeometri. itu adalah penting menjaga ini dalam pikiran ketika manafsirkan hasil pencarian.

Jenis dari dukungan raster terdaftar untuk semua pencarian dalam compatibility table 1. Pencarian melibatkan raster saat ini hanya tersedia untuk backend PostGIS.

## Permintaan Jarak

### Kata Pengantar

Distance calculations with spatial data is tricky because, unfortunately, the Earth is not flat. Some distance queries with fields in a geographic coordinate system may have to be expressed differently because of limitations in PostGIS. Please see the Memilih sebuah SRID section for more details.

### Pencarian Jarak

Ketersediaan: PostGIS, MariaDB, MySQL, Oracle, SpatiaLite, PGRaster (Asli)

Pencarian jarak berikut tersedia:

- `distance_lt`

- `distance_lte`

- `distance_gt`

- `distance_gte`

- `dwithin` (kecuali MariaDB dan MySQL)

Catatan

Untuk mengukur, daripada meminta pada jarak, gunakan fungsi `Distance`.

Pencarian jarak meliputi parameter tuple.

1. Geometri atau raster untuk perhitungan dasar dari; dan

2. Sejumlah atau obyek `Distance` mengandung jarak.

Jika obyek `Distance` digunakan, itu mungkin dinyatakan dalam satuan apapun (SQL dibangkitkan akan menggunakan unit untuk merubah ke bidang tersebut); sebaliknya parameter numerik dianggap berada dalam satuan dari bidang.

Catatan

In PostGIS, `ST_Distance_Sphere` does not limit the geometry types geographic distance queries are performed with. [3] However, these queries may take a long time, as great-circle distances must be calculated on the fly for every row in the query. This is because the spatial index on traditional geometry fields cannot be used.

tUntuk penampilan lebih baik pada permintaan jarak WGS84, pertimbangkan menggunakan geography columns 1 dalam basisdata anda sebagai gantinya karena mereka dapat menggunakan indeks spasial mereka di permintaan jarak. Anda dapat memberitahu GeoDjango menggunakan kolom geografi dengan mengatur `geography=True` dalam penentuan bidang anda.

Sebagai contoh, mari kita katakan kami memiliki sebuah model `SouthTexasCity` (dari GeoDjango distance tests ) pada sebuah sistem kordinat sah diproyeksikan untuk kota-kota dalam Texas selatan:

    from django.contrib.gis.db import models

    class SouthTexasCity(models.Model):
        name = models.CharField(max_length=30)
        # A projected coordinate system (only valid for South Texas!)
        # is used, units are in meters.
        point = models.PointField(srid=32140)

Then distance queries may be performed as follows:

    >>> from django.contrib.gis.geos import GEOSGeometry
    >>> from django.contrib.gis.measure import D  # ``D`` is a shortcut for ``Distance``
    >>> from geoapp.models import SouthTexasCity
    # Distances will be calculated from this point, which does not have to be projected.
    >>> pnt = GEOSGeometry("POINT(-96.876369 29.905320)", srid=4326)
    # If numeric parameter, units of field (meters in this case) are assumed.
    >>> qs = SouthTexasCity.objects.filter(point__distance_lte=(pnt, 7000))
    # Find all Cities within 7 km, > 20 miles away, and > 100 chains away (an obscure unit)
    >>> qs = SouthTexasCity.objects.filter(point__distance_lte=(pnt, D(km=7)))
    >>> qs = SouthTexasCity.objects.filter(point__distance_gte=(pnt, D(mi=20)))
    >>> qs = SouthTexasCity.objects.filter(point__distance_gte=(pnt, D(chain=100)))

Raster queries work the same way by replacing the geometry field `point` with a raster field, or the `pnt` object with a raster object, or both. To specify the band index of a raster input on the right hand side, a 3-tuple can be passed to the lookup as follows:

    >>> qs = SouthTexasCity.objects.filter(point__distance_gte=(rst, 2, D(km=7)))

Dimana pita dengan indeks 2 (pita ketiga) dari raster `rst` akan digunakan untuk pencarian.

## Tabel Kesesuaian

### Pencarian Spasial

Tabel berikut menyediakan ringkasan dari apa pencarian spasial tersedia untuk setiap backend basisdata spasial. Pencarian PostGIS Raster (PGRaster) dibagi kedalam tiga kategori digambarkan dalam raster lookup details 1: dukungan asal `n`, dukungan asal bilateral `B`, dan dukungan perubahan geometri `C`.

Jenis Pencarian | PostGIS | Oracle | MariaDB | MySQL [4] | SpatiaLite | PGRaster
--- | --- | --- | --- | --- | --- | ---
`bbcontains` | X |  | X | X | X | N
`bboverlaps` | X |  | X | X | X | N
`contained` | X |  | X | X | X | N
`contains` | X | X | X | X | X | B
`contains_properly` | X |  |  |  |  | B
`coveredby` | X | X | X (≥ 12.0.1) | X | X | B
`covers` | X | X |  | X | X | B
`crosses` | X |  | X | X | X | C
`disjoint` | X | X | X | X | X | B
`distance_gt` | X | X | X | X | X | N
`distance_gte` | X | X | X | X | X | N
`distance_lt` | X | X | X | X | X | N
`distance_lte` | X | X | X | X | X | N
`dwithin` | X | X |  |  | X | B
`equals` | X | X | X | X | X | C
`exact` | X | X | X | X | X | B
`geom_type` | X | X (≥ 23c) | X | X | X |
`intersects` | X | X | X | X | X | B
`isempty` | X |  |  |  | X |
`isvalid` | X | X | X (≥ 12.0.1) | X | X |
`num_dimensions` | X |  |  |  | X |
`overlaps` | X | X | X | X | X | B
`relate` | X | X | X |  | X | C
`same_as` | X | X | X | X | X | B
`touches` | X | X | X | X | X | B
`within` | X | X | X | X | X | B
`left` | X |  |  |  |  | C
`right` | X |  |  |  |  | C
`overlaps_left` | X |  |  |  |  | B
`overlaps_right` | X |  |  |  |  | B
`overlaps_above` | X |  |  |  |  | C
`overlaps_below` | X |  |  |  |  | C
`strictly_above` | X |  |  |  |  | C
`strictly_below` | X |  |  |  |  | C

### Fungsi basisdata

Tabel berikut menyediakan ringkasan dari apa fungsi-fungsi basisdata khusus-geografis tersedia pada setiap backend spasial.

Fungsi | PostGIS | Oracle | MariaDB | MySQL | SpatiaLite
--- | --- | --- | --- | --- | ---
`Area` | X | X | X | X | X
`AsGeoJSON` | X | X | X | X | X
`AsGML` | X | X |  |  | X
`AsKML` | X |  |  |  | X
`AsSVG` | X |  |  |  | X
`AsWKB` | X | X | X | X | X
`AsWKT` | X | X | X | X | X
`Azimuth` | X |  |  |  | X (LWGEOM/RTTOPO)
`BoundingCircle` | X | X |  |  | X (≥ 5.1)
`Centroid` | X | X | X | X | X
`ClosestPoint` | X |  |  |  | X
`Difference` | X | X | X | X | X
`Distance` | X | X | X | X | X
`Envelope` | X | X | X | X | X
`ForcePolygonCW` | X |  |  |  | X
`FromWKB` | X | X | X | X | X
`FromWKT` | X | X | X | X | X
`GeoHash` | X |  | X (≥ 12.0.1) | X | X (LWGEOM/RTTOPO)
`GeometryDistance` | X |  |  |  |
`GeometryType` | X | X (≥ 23c) | X | X | X
`Intersection` | X | X | X | X | X
`IsEmpty` | X |  |  |  | X
`IsValid` | X | X | X (≥ 12.0.1) | X | X
`Length` | X | X | X | X | X
`LineLocatePoint` | X |  |  |  | X
`MakeValid` | X |  |  |  | X (LWGEOM/RTTOPO)
`MemSize` | X |  |  |  |
`NumDimensions` | X |  |  |  | X
`NumGeometries` | X | X | X | X | X
`NumPoints` | X | X | X | X | X
`Perimeter` | X | X |  |  | X
`PointOnSurface` | X | X | X |  | X
`Reverse` | X | X |  |  | X
`Rotate` | X |  |  |  |
`Scale` | X |  |  |  | X
`SnapToGrid` | X |  |  |  | X
`SymDifference` | X | X | X | X | X
`Transform` | X | X |  |  | X
`Translate` | X |  |  |  | X
`Union` | X | X | X | X | X

### Fungsi Kumpulan

The following table provides a summary of what GIS-specific aggregate functions are available on each spatial backend.

Kumpulan | PostGIS | Oracle | MariaDB | MySQL | SpatiaLite
--- | --- | --- | --- | --- | ---
`Collect` | X |  | X (≥ 12.0.1) | X (≥ 8.0.24) | X
`Extent` | X | X |  |  | X
`Extent3D` | X |  |  |  |
`MakeLine` | X |  |  |  | X
`Union` | X | X |  |  | X

Catatan kaki

[1]

See Open Geospatial Consortium, Inc., OpenGIS Simple Feature Specification For SQL, Document 99-049 (May 5, 1999), at Ch. 3.2.5, p. 3-11 (SQL Textual Representation of Geometry).

[2]

Lihat PostGIS EWKB, EWKT and Canonical Forms, Dokumentasi PostGIS bab 4.1.2.

[3]

Lihat PostGIS documentation pada `ST_DistanceSphere`.

[4]

Mengacu bagian Batasan Spasial MySQL untuk rincian lebih.