---
title: "Fóntais allmhairithe sonraí Layermapping"
version: 6.0
locale: ga
source: https://docs.djangoproject.com/ga/6.0/ref/contrib/gis/layermapping/
canonical: https://djangodocs.dev/ga/6.0/ref/contrib/gis/layermapping/
---
# Fóntais allmhairithe sonraí `Layermapping`

Soláthraíonn an rang:class: LayerMapping bealach chun ábhar comhaid sonraí spásúla veicteora (m.sh. comhaid chruthach) a mhapáil i samhlacha GeoDjango.

D'fhás an fóntais seo as riachtanais phearsanta an údair chun deireadh a chur leis an athrá cód a chuaigh chun geoiméadraí agus réimsí a tharraingt as ciseal veicteora, ag tiontú go córas comhordaithe eile (m.sh. WGS84), agus ansin a chur isteach i samhail GeoDjango.

> **Note**
>
> Úsáid o:class: LayerMapping teastaíonn GDAL.

> **Warning**
>
> GIS data sources, like shapefiles, may be very large. If you find that
> [`LayerMapping`](#django.contrib.gis.utils.LayerMapping) is using too much memory, set [`DEBUG`](/ga/6.0/ref/settings/#std-setting-DEBUG) to
> `False` in your settings. When [`DEBUG`](/ga/6.0/ref/settings/#std-setting-DEBUG) is set to `True`,
> Django [automatically logs](/ga/6.0/faq/models/#faq-see-raw-sql-queries) *every* SQL
> query -- and when SQL statements contain geometries, this may consume more
> memory than is typical.

## Sampla

1. Teastaíonn foinse sonraí le tacaíocht ó GDAL uait, cosúil le comhaid chruthach (anseo táimid ag úsáid comhad cruth polygon simplí, `test_poly.shp`, le trí ghné):

```pycon
>>> from django.contrib.gis.gdal import DataSource
>>> ds = DataSource("test_poly.shp")
>>> layer = ds[0]
>>> print(layer.fields)  # Exploring the fields in the layer, we only want the 'str' field.
['float', 'int', 'str']
>>> print(len(layer))  # getting the number of features in the layer (should be 3)
3
>>> print(layer.geom_type)  # Should be 'Polygon'
Polygon
>>> print(layer.srs)  # WGS84 in WKT
GEOGCS["GCS_WGS_1984",
    DATUM["WGS_1984",
        SPHEROID["WGS_1984",6378137,298.257223563]],
    PRIMEM["Greenwich",0],
    UNIT["Degree",0.017453292519943295]]
```

1. Anois sainmhínímid ár samhail Django comhfhreagrach (déan cinnte go n-úsáidtear: djadmin: migrate):

   ```
   from django.contrib.gis.db import models

   class TestGeo(models.Model):
       name = models.CharField(max_length=25)  # corresponds to the 'str' field
       poly = models.PolygonField(srid=4269)  # we want our model in a different SRID

       def __str__(self):
           return "Name: %s" % self.name
   ```
2. Úsáid: aicme: LayerMapping chun na gnéithe go léir a bhaint agus iad a chur sa bhunachar sonraí:

```pycon
>>> from django.contrib.gis.utils import LayerMapping
>>> from geoapp.models import TestGeo
>>> mapping = {
...     "name": "str",  # The 'name' model field maps to the 'str' layer field.
...     "poly": "POLYGON",  # For geometry fields use OGC name.
... }  # The mapping is a dictionary
>>> lm = LayerMapping(TestGeo, "test_poly.shp", mapping)
>>> lm.save(verbose=True)  # Save the layermap, imports the data.
Saved: Name: 1
Saved: Name: 2
Saved: Name: 3
```

Here, [`LayerMapping`](#django.contrib.gis.utils.LayerMapping) transformed the three geometries from the shapefile
in their original spatial reference system (WGS84) to the spatial reference
system of the GeoDjango model (NAD83). If no spatial reference system is
defined for the layer, use the `source_srs` keyword with a
[`SpatialReference`](/ga/6.0/ref/contrib/gis/gdal/#django.contrib.gis.gdal.SpatialReference) object to specify one.

## `Sraith Maping` API

#### `class LayerMapping(model, data_source, mapping, layer=0, source_srs=None, encoding=None, transaction_mode='commit_on_success', transform=True, unique=True, using='default')`

Is iad seo a leanas na hargóintí agus na heochairfhocail a d'fhéadfaí a úsáid le linn rudaí Layermapping\` a chur isteach.

| Argóint | Cur síos |
| --- | --- |
| Samhail \`\` | An tsamhail gheografach, *ní* sampla. |
| `foinse sonraí` | The path to the OGR-supported data source file<br>(e.g., a shapefile). Also accepts<br>[`django.contrib.gis.gdal.DataSource`](/ga/6.0/ref/contrib/gis/gdal/#django.contrib.gis.gdal.DataSource) instances. |
| `mapaitheo` | Foclóir: is teaghráin iad na heochracha a fhreagraíonn don réimse samhail, agus freagraíonn luachanna d'ainmneacha réimse teaghrán don ghné OGR, nó más réimse samhail is geografach é ansin ba chóir go bhfreagródh sé do chineál geoiméadrachta OGR, m.sh., `` `POINT ``, LINESTRING\`, POLYGON'. |

| Argóintí Eochair |  |
| --- | --- |
| `sraithe` | Innéacs an chiseal le húsáid ón bhFoinse Sonraí (réamhshocraithe go 0) |
| `foinse_srs` | Use this to specify the source SRS manually (for<br>example, some shapefiles don't come with a `'.prj'`<br>file). An integer SRID, WKT or PROJ strings, and<br>[`django.contrib.gis.gdal.SpatialReference`](/ga/6.0/ref/contrib/gis/gdal/#django.contrib.gis.gdal.SpatialReference)<br>objects are accepted. |
| ionchódú \`\` | Specifies the character set encoding of the strings<br>in the OGR data source. For example, `'latin-1'`,<br>`'utf-8'`, and `'cp437'` are all valid encoding<br>parameters. |
| `mod_idirbhearta` | D'fhéadfadh sé a bheith `` `commit_on_success' `` (réamhshocraithe) nó `` `'autochommit' ``. |
| `` `claochl `` | Setting this to False will disable coordinate<br>transformations. In other words, geometries will<br>be inserted into the database unmodified from their<br>original state in the data source. |
| `uath` | Setting this to the name, or a tuple of names,<br>from the given  model will create models unique<br>only to the given name(s). Geometries from<br>each feature will be added into the collection<br>associated with the unique model. Forces<br>the transaction mode to be `'autocommit'`. |
| `` `Úsáid `` | Socraíonn an bunachar sonraí le húsáid agus sonraí spásúla á iompórtá Is é réamhshocraithe 'default' . |

### save () Argóintí Eochairfhocal

#### `LayerMapping.save(verbose=False, fid_range=False, step=False, progress=False, silent=False, stream=sys.stdout, strict=False)`

The `save()` method also accepts keywords. These keywords are
used for controlling output logging, error handling, and for importing
specific feature ranges.

| Argóintí Eochairfhocal | Cur síos |
| --- | --- |
| `raon fid` | May be set with a slice or tuple of<br>(begin, end) feature ID's to map from<br>the data source. In other words, this<br>keyword enables the user to selectively<br>import a subset range of features in the<br>geographic data source. |
| `` `dul chun cinne `` | When this keyword is set, status information<br>will be printed giving the number of features<br>processed and successfully saved. By default,<br>progress information will be printed every 1000<br>features processed, however, this default may<br>be overridden by setting this keyword with an<br>integer for the desired interval. |
| `ciúna` | De réir réamhshocraithe, clóitear fógraí earráide neamh-mharfach chuig sys.stdout\`, ach féadfar an eochairfhocal seo a shocrú chun na fógraí seo a dhíchumasú. |
| `céime` | Má shocraítear é le sláimhir, tarlóidh idirbhearta ag gach eatramh céim. Mar shampla, má tharlódh sé `step = 1000`, tiomantas tar éis na 1,000ú gné, an 2,000ú gné srl. |
| `sruth` | Status information will be written to this file<br>handle. Defaults to using `sys.stdout`, but<br>any object with a `write` method is supported. |
| docht \`\` | Execution of the model mapping will cease upon<br>the first error encountered. The default value<br>(`False`)<br>behavior is to attempt to continue. |
| `Verbose` | Má shocraítear é, clófar faisnéis ina dhiaidh sin gach samhail sábháil a fhorghníomhú ar an mbunachar sonraí. |

## Fabhtcheartú

### Rith as cuimhne

As noted in the warning at the top of this section, Django stores all SQL
queries when `DEBUG=True`. Set `DEBUG=False` in your settings, and this
should stop excessive memory use when running `LayerMapping` scripts.

### MySQL: earráid `max_allowed_packet`

Má thagann tú ar an earráid seo a leanas agus tú ag úsáid `LayerMapping` agus MySQL:

```pytb
OperationalError: (1153, "Got a packet bigger than 'max_allowed_packet' bytes")
```

Then the solution is to increase the value of the `max_allowed_packet`
setting in your MySQL configuration. For example, the default value may
be something low like one megabyte -- the setting may be modified in MySQL's
configuration file (`my.cnf`) in the `[mysqld]` section:

```ini
max_allowed_packet = 10M
```
