2008-08-06 02:13:06 +08:00
|
|
|
# LayerMapping -- A Django Model/OGR Layer Mapping Utility
|
|
|
|
"""
|
|
|
|
The LayerMapping class provides a way to map the contents of OGR
|
|
|
|
vector files (e.g. SHP files) to Geographic-enabled Django models.
|
|
|
|
|
2009-12-22 23:18:51 +08:00
|
|
|
For more information, please consult the GeoDjango documentation:
|
2015-05-07 00:01:23 +08:00
|
|
|
https://docs.djangoproject.com/en/dev/ref/contrib/gis/layermapping/
|
2008-08-06 02:13:06 +08:00
|
|
|
"""
|
|
|
|
import sys
|
2013-09-30 23:55:14 +08:00
|
|
|
from decimal import Decimal, InvalidOperation as DecimalInvalidOperation
|
2020-11-28 14:28:03 +08:00
|
|
|
from pathlib import Path
|
2015-01-28 20:35:27 +08:00
|
|
|
|
2008-08-06 02:13:06 +08:00
|
|
|
from django.contrib.gis.db.models import GeometryField
|
2015-01-28 20:35:27 +08:00
|
|
|
from django.contrib.gis.gdal import (
|
|
|
|
CoordTransform, DataSource, GDALException, OGRGeometry, OGRGeomType,
|
|
|
|
SpatialReference,
|
|
|
|
)
|
2011-07-13 17:35:51 +08:00
|
|
|
from django.contrib.gis.gdal.field import (
|
2018-02-03 03:44:07 +08:00
|
|
|
OFTDate, OFTDateTime, OFTInteger, OFTInteger64, OFTReal, OFTString,
|
|
|
|
OFTTime,
|
2015-01-28 20:35:27 +08:00
|
|
|
)
|
|
|
|
from django.core.exceptions import FieldDoesNotExist, ObjectDoesNotExist
|
|
|
|
from django.db import connections, models, router, transaction
|
2017-01-26 17:08:08 +08:00
|
|
|
from django.utils.encoding import force_str
|
2012-10-07 04:56:47 +08:00
|
|
|
|
2008-08-06 02:13:06 +08:00
|
|
|
|
|
|
|
# LayerMapping exceptions.
|
2013-10-17 16:17:41 +08:00
|
|
|
class LayerMapError(Exception):
|
|
|
|
pass
|
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2013-10-17 16:17:41 +08:00
|
|
|
class InvalidString(LayerMapError):
|
|
|
|
pass
|
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2013-10-17 16:17:41 +08:00
|
|
|
class InvalidDecimal(LayerMapError):
|
|
|
|
pass
|
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2013-10-17 16:17:41 +08:00
|
|
|
class InvalidInteger(LayerMapError):
|
|
|
|
pass
|
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2013-10-17 16:17:41 +08:00
|
|
|
class MissingForeignKey(LayerMapError):
|
|
|
|
pass
|
2008-08-06 02:13:06 +08:00
|
|
|
|
2013-11-03 04:12:09 +08:00
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
class LayerMapping:
|
2008-08-06 02:13:06 +08:00
|
|
|
"A class that maps OGR Layers to GeoDjango Models."
|
2009-12-22 23:18:51 +08:00
|
|
|
|
2008-08-06 02:13:06 +08:00
|
|
|
# Acceptable 'base' types for a multi-geometry type.
|
2019-01-03 07:18:19 +08:00
|
|
|
MULTI_TYPES = {
|
|
|
|
1: OGRGeomType('MultiPoint'),
|
|
|
|
2: OGRGeomType('MultiLineString'),
|
|
|
|
3: OGRGeomType('MultiPolygon'),
|
|
|
|
OGRGeomType('Point25D').num: OGRGeomType('MultiPoint25D'),
|
|
|
|
OGRGeomType('LineString25D').num: OGRGeomType('MultiLineString25D'),
|
|
|
|
OGRGeomType('Polygon25D').num: OGRGeomType('MultiPolygon25D'),
|
|
|
|
}
|
2008-08-06 02:13:06 +08:00
|
|
|
# Acceptable Django field types and corresponding acceptable OGR
|
|
|
|
# counterparts.
|
|
|
|
FIELD_TYPES = {
|
2013-10-27 09:27:42 +08:00
|
|
|
models.AutoField: OFTInteger,
|
2015-07-02 16:43:15 +08:00
|
|
|
models.BigAutoField: OFTInteger64,
|
2019-07-27 05:05:22 +08:00
|
|
|
models.SmallAutoField: OFTInteger,
|
2019-02-01 08:50:16 +08:00
|
|
|
models.BooleanField: (OFTInteger, OFTReal, OFTString),
|
2013-10-27 09:27:42 +08:00
|
|
|
models.IntegerField: (OFTInteger, OFTReal, OFTString),
|
|
|
|
models.FloatField: (OFTInteger, OFTReal),
|
|
|
|
models.DateField: OFTDate,
|
|
|
|
models.DateTimeField: OFTDateTime,
|
|
|
|
models.EmailField: OFTString,
|
|
|
|
models.TimeField: OFTTime,
|
|
|
|
models.DecimalField: (OFTInteger, OFTReal),
|
|
|
|
models.CharField: OFTString,
|
|
|
|
models.SlugField: OFTString,
|
|
|
|
models.TextField: OFTString,
|
|
|
|
models.URLField: OFTString,
|
2019-02-01 08:50:16 +08:00
|
|
|
models.UUIDField: OFTString,
|
2013-10-27 09:27:42 +08:00
|
|
|
models.BigIntegerField: (OFTInteger, OFTReal, OFTString),
|
|
|
|
models.SmallIntegerField: (OFTInteger, OFTReal, OFTString),
|
2019-10-16 20:32:12 +08:00
|
|
|
models.PositiveBigIntegerField: (OFTInteger, OFTReal, OFTString),
|
2019-02-08 05:25:15 +08:00
|
|
|
models.PositiveIntegerField: (OFTInteger, OFTReal, OFTString),
|
2013-10-27 09:27:42 +08:00
|
|
|
models.PositiveSmallIntegerField: (OFTInteger, OFTReal, OFTString),
|
2013-10-18 17:02:43 +08:00
|
|
|
}
|
2008-08-06 02:13:06 +08:00
|
|
|
|
2009-12-22 23:18:51 +08:00
|
|
|
def __init__(self, model, data, mapping, layer=0,
|
2012-10-07 04:56:47 +08:00
|
|
|
source_srs=None, encoding='utf-8',
|
2009-12-22 23:18:51 +08:00
|
|
|
transaction_mode='commit_on_success',
|
2012-09-20 16:08:08 +08:00
|
|
|
transform=True, unique=None, using=None):
|
2008-08-06 02:13:06 +08:00
|
|
|
"""
|
|
|
|
A LayerMapping object is initialized using the given Model (not an instance),
|
|
|
|
a DataSource (or string path to an OGR-supported data file), and a mapping
|
|
|
|
dictionary. See the module level docstring for more details and keyword
|
|
|
|
argument usage.
|
|
|
|
"""
|
|
|
|
# Getting the DataSource and the associated Layer.
|
2020-11-28 14:28:03 +08:00
|
|
|
if isinstance(data, (str, Path)):
|
2012-10-07 04:56:47 +08:00
|
|
|
self.ds = DataSource(data, encoding=encoding)
|
2008-08-06 02:13:06 +08:00
|
|
|
else:
|
|
|
|
self.ds = data
|
|
|
|
self.layer = self.ds[layer]
|
|
|
|
|
2012-09-20 16:08:08 +08:00
|
|
|
self.using = using if using is not None else router.db_for_write(model)
|
|
|
|
self.spatial_backend = connections[self.using].ops
|
2009-12-22 23:18:51 +08:00
|
|
|
|
2008-09-10 03:19:51 +08:00
|
|
|
# Setting the mapping & model attributes.
|
2008-08-06 02:13:06 +08:00
|
|
|
self.mapping = mapping
|
|
|
|
self.model = model
|
2009-12-22 23:18:51 +08:00
|
|
|
|
2014-04-27 01:18:45 +08:00
|
|
|
# Checking the layer -- initialization of the object will fail if
|
2008-09-10 03:19:51 +08:00
|
|
|
# things don't check out before hand.
|
|
|
|
self.check_layer()
|
|
|
|
|
2009-12-22 23:18:51 +08:00
|
|
|
# Getting the geometry column associated with the model (an
|
2008-09-10 03:19:51 +08:00
|
|
|
# exception will be raised if there is no geometry column).
|
2014-08-22 00:47:57 +08:00
|
|
|
if connections[self.using].features.supports_transform:
|
2009-12-25 22:37:57 +08:00
|
|
|
self.geo_field = self.geometry_field()
|
2014-08-22 00:47:57 +08:00
|
|
|
else:
|
|
|
|
transform = False
|
2008-08-06 02:13:06 +08:00
|
|
|
|
|
|
|
# Checking the source spatial reference system, and getting
|
|
|
|
# the coordinate transformation object (unless the `transform`
|
|
|
|
# keyword is set to False)
|
|
|
|
if transform:
|
|
|
|
self.source_srs = self.check_srs(source_srs)
|
|
|
|
self.transform = self.coord_transform()
|
|
|
|
else:
|
|
|
|
self.transform = transform
|
|
|
|
|
|
|
|
# Setting the encoding for OFTString fields, if specified.
|
|
|
|
if encoding:
|
|
|
|
# Making sure the encoding exists, if not a LookupError
|
|
|
|
# exception will be thrown.
|
|
|
|
from codecs import lookup
|
|
|
|
lookup(encoding)
|
|
|
|
self.encoding = encoding
|
|
|
|
else:
|
|
|
|
self.encoding = None
|
|
|
|
|
|
|
|
if unique:
|
|
|
|
self.check_unique(unique)
|
2013-11-03 05:02:56 +08:00
|
|
|
transaction_mode = 'autocommit' # Has to be set to autocommit.
|
2008-08-06 02:13:06 +08:00
|
|
|
self.unique = unique
|
|
|
|
else:
|
|
|
|
self.unique = None
|
|
|
|
|
2009-12-22 23:18:51 +08:00
|
|
|
# Setting the transaction decorator with the function in the
|
2008-08-06 02:13:06 +08:00
|
|
|
# transaction modes dictionary.
|
2013-03-12 03:03:17 +08:00
|
|
|
self.transaction_mode = transaction_mode
|
|
|
|
if transaction_mode == 'autocommit':
|
|
|
|
self.transaction_decorator = None
|
|
|
|
elif transaction_mode == 'commit_on_success':
|
|
|
|
self.transaction_decorator = transaction.atomic
|
2008-08-06 02:13:06 +08:00
|
|
|
else:
|
|
|
|
raise LayerMapError('Unrecognized transaction mode: %s' % transaction_mode)
|
2009-12-22 23:18:51 +08:00
|
|
|
|
2015-02-06 02:25:34 +08:00
|
|
|
# #### Checking routines used during initialization ####
|
2008-08-06 02:13:06 +08:00
|
|
|
def check_fid_range(self, fid_range):
|
2017-01-25 04:31:57 +08:00
|
|
|
"Check the `fid_range` keyword."
|
2008-08-06 02:13:06 +08:00
|
|
|
if fid_range:
|
|
|
|
if isinstance(fid_range, (tuple, list)):
|
|
|
|
return slice(*fid_range)
|
|
|
|
elif isinstance(fid_range, slice):
|
|
|
|
return fid_range
|
|
|
|
else:
|
|
|
|
raise TypeError
|
|
|
|
else:
|
|
|
|
return None
|
|
|
|
|
|
|
|
def check_layer(self):
|
|
|
|
"""
|
2017-01-25 04:31:57 +08:00
|
|
|
Check the Layer metadata and ensure that it's compatible with the
|
|
|
|
mapping information and model. Unlike previous revisions, there is no
|
|
|
|
need to increment through each feature in the Layer.
|
2008-08-06 02:13:06 +08:00
|
|
|
"""
|
|
|
|
# The geometry field of the model is set here.
|
2008-09-10 03:19:51 +08:00
|
|
|
# TODO: Support more than one geometry field / model. However, this
|
|
|
|
# depends on the GDAL Driver in use.
|
2008-08-06 02:13:06 +08:00
|
|
|
self.geom_field = False
|
|
|
|
self.fields = {}
|
|
|
|
|
|
|
|
# Getting lists of the field names and the field types available in
|
|
|
|
# the OGR Layer.
|
|
|
|
ogr_fields = self.layer.fields
|
|
|
|
ogr_field_types = self.layer.field_types
|
|
|
|
|
|
|
|
# Function for determining if the OGR mapping field is in the Layer.
|
|
|
|
def check_ogr_fld(ogr_map_fld):
|
|
|
|
try:
|
|
|
|
idx = ogr_fields.index(ogr_map_fld)
|
|
|
|
except ValueError:
|
|
|
|
raise LayerMapError('Given mapping OGR field "%s" not found in OGR Layer.' % ogr_map_fld)
|
|
|
|
return idx
|
|
|
|
|
|
|
|
# No need to increment through each feature in the model, simply check
|
|
|
|
# the Layer metadata against what was given in the mapping dictionary.
|
|
|
|
for field_name, ogr_name in self.mapping.items():
|
|
|
|
# Ensuring that a corresponding field exists in the model
|
|
|
|
# for the given field name in the mapping.
|
|
|
|
try:
|
|
|
|
model_field = self.model._meta.get_field(field_name)
|
2015-01-02 23:14:23 +08:00
|
|
|
except FieldDoesNotExist:
|
2008-08-06 02:13:06 +08:00
|
|
|
raise LayerMapError('Given mapping field "%s" not in given Model fields.' % field_name)
|
|
|
|
|
|
|
|
# Getting the string name for the Django field class (e.g., 'PointField').
|
|
|
|
fld_name = model_field.__class__.__name__
|
|
|
|
|
|
|
|
if isinstance(model_field, GeometryField):
|
|
|
|
if self.geom_field:
|
|
|
|
raise LayerMapError('LayerMapping does not support more than one GeometryField per model.')
|
|
|
|
|
2009-11-17 02:49:00 +08:00
|
|
|
# Getting the coordinate dimension of the geometry field.
|
|
|
|
coord_dim = model_field.dim
|
|
|
|
|
2008-08-06 02:13:06 +08:00
|
|
|
try:
|
2009-11-17 02:49:00 +08:00
|
|
|
if coord_dim == 3:
|
|
|
|
gtype = OGRGeomType(ogr_name + '25D')
|
|
|
|
else:
|
|
|
|
gtype = OGRGeomType(ogr_name)
|
2014-12-18 05:00:05 +08:00
|
|
|
except GDALException:
|
2008-08-06 02:13:06 +08:00
|
|
|
raise LayerMapError('Invalid mapping for GeometryField "%s".' % field_name)
|
|
|
|
|
|
|
|
# Making sure that the OGR Layer's Geometry is compatible.
|
|
|
|
ltype = self.layer.geom_type
|
2009-11-17 02:49:00 +08:00
|
|
|
if not (ltype.name.startswith(gtype.name) or self.make_multi(ltype, model_field)):
|
2010-03-30 02:33:23 +08:00
|
|
|
raise LayerMapError('Invalid mapping geometry; model has %s%s, '
|
|
|
|
'layer geometry type is %s.' %
|
2013-05-17 22:33:36 +08:00
|
|
|
(fld_name, '(dim=3)' if coord_dim == 3 else '', ltype))
|
2008-08-06 02:13:06 +08:00
|
|
|
|
|
|
|
# Setting the `geom_field` attribute w/the name of the model field
|
2009-11-17 02:49:00 +08:00
|
|
|
# that is a Geometry. Also setting the coordinate dimension
|
|
|
|
# attribute.
|
2008-08-06 02:13:06 +08:00
|
|
|
self.geom_field = field_name
|
2009-11-17 02:49:00 +08:00
|
|
|
self.coord_dim = coord_dim
|
2008-08-06 02:13:06 +08:00
|
|
|
fields_val = model_field
|
|
|
|
elif isinstance(model_field, models.ForeignKey):
|
|
|
|
if isinstance(ogr_name, dict):
|
|
|
|
# Is every given related model mapping field in the Layer?
|
2015-02-26 22:19:17 +08:00
|
|
|
rel_model = model_field.remote_field.model
|
2009-12-22 23:18:51 +08:00
|
|
|
for rel_name, ogr_field in ogr_name.items():
|
2008-08-06 02:13:06 +08:00
|
|
|
idx = check_ogr_fld(ogr_field)
|
|
|
|
try:
|
2013-09-08 23:05:16 +08:00
|
|
|
rel_model._meta.get_field(rel_name)
|
2015-01-02 23:14:23 +08:00
|
|
|
except FieldDoesNotExist:
|
2009-12-22 23:18:51 +08:00
|
|
|
raise LayerMapError('ForeignKey mapping field "%s" not in %s fields.' %
|
2008-08-06 02:13:06 +08:00
|
|
|
(rel_name, rel_model.__class__.__name__))
|
|
|
|
fields_val = rel_model
|
|
|
|
else:
|
|
|
|
raise TypeError('ForeignKey mapping must be of dictionary type.')
|
|
|
|
else:
|
|
|
|
# Is the model field type supported by LayerMapping?
|
2014-03-31 03:11:05 +08:00
|
|
|
if model_field.__class__ not in self.FIELD_TYPES:
|
2008-08-06 02:13:06 +08:00
|
|
|
raise LayerMapError('Django field type "%s" has no OGR mapping (yet).' % fld_name)
|
|
|
|
|
|
|
|
# Is the OGR field in the Layer?
|
|
|
|
idx = check_ogr_fld(ogr_name)
|
|
|
|
ogr_field = ogr_field_types[idx]
|
|
|
|
|
|
|
|
# Can the OGR field type be mapped to the Django field type?
|
|
|
|
if not issubclass(ogr_field, self.FIELD_TYPES[model_field.__class__]):
|
2009-12-22 23:18:51 +08:00
|
|
|
raise LayerMapError('OGR field "%s" (of type %s) cannot be mapped to Django %s.' %
|
2008-08-06 02:13:06 +08:00
|
|
|
(ogr_field, ogr_field.__name__, fld_name))
|
|
|
|
fields_val = model_field
|
2009-12-22 23:18:51 +08:00
|
|
|
|
2008-08-06 02:13:06 +08:00
|
|
|
self.fields[field_name] = fields_val
|
|
|
|
|
|
|
|
def check_srs(self, source_srs):
|
2017-01-25 04:31:57 +08:00
|
|
|
"Check the compatibility of the given spatial reference object."
|
2009-12-22 23:18:51 +08:00
|
|
|
|
2008-08-06 02:13:06 +08:00
|
|
|
if isinstance(source_srs, SpatialReference):
|
|
|
|
sr = source_srs
|
2009-12-22 23:18:51 +08:00
|
|
|
elif isinstance(source_srs, self.spatial_backend.spatial_ref_sys()):
|
2008-08-06 02:13:06 +08:00
|
|
|
sr = source_srs.srs
|
2016-12-29 23:27:49 +08:00
|
|
|
elif isinstance(source_srs, (int, str)):
|
2008-08-06 02:13:06 +08:00
|
|
|
sr = SpatialReference(source_srs)
|
|
|
|
else:
|
|
|
|
# Otherwise just pulling the SpatialReference from the layer
|
|
|
|
sr = self.layer.srs
|
2009-12-22 23:18:51 +08:00
|
|
|
|
2008-08-06 02:13:06 +08:00
|
|
|
if not sr:
|
|
|
|
raise LayerMapError('No source reference system defined.')
|
|
|
|
else:
|
|
|
|
return sr
|
|
|
|
|
|
|
|
def check_unique(self, unique):
|
2017-01-25 04:31:57 +08:00
|
|
|
"Check the `unique` keyword parameter -- may be a sequence or string."
|
2008-08-06 02:13:06 +08:00
|
|
|
if isinstance(unique, (list, tuple)):
|
|
|
|
# List of fields to determine uniqueness with
|
2009-12-22 23:18:51 +08:00
|
|
|
for attr in unique:
|
2014-03-31 03:11:05 +08:00
|
|
|
if attr not in self.mapping:
|
2013-10-17 16:17:41 +08:00
|
|
|
raise ValueError
|
2016-12-29 23:27:49 +08:00
|
|
|
elif isinstance(unique, str):
|
2008-08-06 02:13:06 +08:00
|
|
|
# Only a single field passed in.
|
2013-10-17 16:17:41 +08:00
|
|
|
if unique not in self.mapping:
|
|
|
|
raise ValueError
|
2008-08-06 02:13:06 +08:00
|
|
|
else:
|
|
|
|
raise TypeError('Unique keyword argument must be set with a tuple, list, or string.')
|
|
|
|
|
2013-11-03 05:02:56 +08:00
|
|
|
# Keyword argument retrieval routines ####
|
2008-08-06 02:13:06 +08:00
|
|
|
def feature_kwargs(self, feat):
|
|
|
|
"""
|
2017-01-25 04:31:57 +08:00
|
|
|
Given an OGR Feature, return a dictionary of keyword arguments for
|
|
|
|
constructing the mapped model.
|
2008-08-06 02:13:06 +08:00
|
|
|
"""
|
|
|
|
# The keyword arguments for model construction.
|
|
|
|
kwargs = {}
|
|
|
|
|
|
|
|
# Incrementing through each model field and OGR field in the
|
|
|
|
# dictionary mapping.
|
|
|
|
for field_name, ogr_name in self.mapping.items():
|
|
|
|
model_field = self.fields[field_name]
|
2009-12-22 23:18:51 +08:00
|
|
|
|
2008-08-06 02:13:06 +08:00
|
|
|
if isinstance(model_field, GeometryField):
|
|
|
|
# Verify OGR geometry.
|
2011-03-15 10:26:37 +08:00
|
|
|
try:
|
|
|
|
val = self.verify_geom(feat.geom, model_field)
|
2014-12-18 05:00:05 +08:00
|
|
|
except GDALException:
|
2011-03-15 10:26:37 +08:00
|
|
|
raise LayerMapError('Could not retrieve geometry from feature.')
|
2008-08-06 02:13:06 +08:00
|
|
|
elif isinstance(model_field, models.base.ModelBase):
|
|
|
|
# The related _model_, not a field was passed in -- indicating
|
|
|
|
# another mapping for the related Model.
|
|
|
|
val = self.verify_fk(feat, model_field, ogr_name)
|
|
|
|
else:
|
|
|
|
# Otherwise, verify OGR Field type.
|
|
|
|
val = self.verify_ogr_field(feat[ogr_name], model_field)
|
|
|
|
|
|
|
|
# Setting the keyword arguments for the field name with the
|
|
|
|
# value obtained above.
|
|
|
|
kwargs[field_name] = val
|
2009-12-22 23:18:51 +08:00
|
|
|
|
2008-08-06 02:13:06 +08:00
|
|
|
return kwargs
|
|
|
|
|
|
|
|
def unique_kwargs(self, kwargs):
|
|
|
|
"""
|
2017-01-25 04:31:57 +08:00
|
|
|
Given the feature keyword arguments (from `feature_kwargs`), construct
|
|
|
|
and return the uniqueness keyword arguments -- a subset of the feature
|
|
|
|
kwargs.
|
2008-08-06 02:13:06 +08:00
|
|
|
"""
|
2016-12-29 23:27:49 +08:00
|
|
|
if isinstance(self.unique, str):
|
2013-10-27 09:27:42 +08:00
|
|
|
return {self.unique: kwargs[self.unique]}
|
2008-08-06 02:13:06 +08:00
|
|
|
else:
|
2014-12-07 05:00:09 +08:00
|
|
|
return {fld: kwargs[fld] for fld in self.unique}
|
2008-08-06 02:13:06 +08:00
|
|
|
|
2015-02-06 02:25:34 +08:00
|
|
|
# #### Verification routines used in constructing model keyword arguments. ####
|
2008-08-06 02:13:06 +08:00
|
|
|
def verify_ogr_field(self, ogr_field, model_field):
|
|
|
|
"""
|
2017-01-25 04:31:57 +08:00
|
|
|
Verify if the OGR Field contents are acceptable to the model field. If
|
|
|
|
they are, return the verified value, otherwise raise an exception.
|
2008-08-06 02:13:06 +08:00
|
|
|
"""
|
2009-12-22 23:18:51 +08:00
|
|
|
if (isinstance(ogr_field, OFTString) and
|
2013-11-26 17:43:46 +08:00
|
|
|
isinstance(model_field, (models.CharField, models.TextField))):
|
2019-02-01 08:50:16 +08:00
|
|
|
if self.encoding and ogr_field.value is not None:
|
2008-08-06 02:13:06 +08:00
|
|
|
# The encoding for OGR data sources may be specified here
|
|
|
|
# (e.g., 'cp437' for Census Bureau boundary files).
|
2017-01-26 17:08:08 +08:00
|
|
|
val = force_str(ogr_field.value, self.encoding)
|
2008-08-06 02:13:06 +08:00
|
|
|
else:
|
|
|
|
val = ogr_field.value
|
2019-02-01 08:50:16 +08:00
|
|
|
if model_field.max_length and val is not None and len(val) > model_field.max_length:
|
2014-09-19 00:54:38 +08:00
|
|
|
raise InvalidString('%s model field maximum string length is %s, given %s characters.' %
|
|
|
|
(model_field.name, model_field.max_length, len(val)))
|
2008-08-06 02:13:06 +08:00
|
|
|
elif isinstance(ogr_field, OFTReal) and isinstance(model_field, models.DecimalField):
|
|
|
|
try:
|
|
|
|
# Creating an instance of the Decimal value to use.
|
|
|
|
d = Decimal(str(ogr_field.value))
|
2013-09-30 23:55:14 +08:00
|
|
|
except DecimalInvalidOperation:
|
2008-08-06 02:13:06 +08:00
|
|
|
raise InvalidDecimal('Could not construct decimal from: %s' % ogr_field.value)
|
|
|
|
|
|
|
|
# Getting the decimal value as a tuple.
|
|
|
|
dtup = d.as_tuple()
|
|
|
|
digits = dtup[1]
|
2013-11-03 05:02:56 +08:00
|
|
|
d_idx = dtup[2] # index where the decimal is
|
2008-08-06 02:13:06 +08:00
|
|
|
|
|
|
|
# Maximum amount of precision, or digits to the left of the decimal.
|
|
|
|
max_prec = model_field.max_digits - model_field.decimal_places
|
|
|
|
|
2009-12-22 23:18:51 +08:00
|
|
|
# Getting the digits to the left of the decimal place for the
|
2008-08-06 02:13:06 +08:00
|
|
|
# given decimal.
|
|
|
|
if d_idx < 0:
|
|
|
|
n_prec = len(digits[:d_idx])
|
|
|
|
else:
|
|
|
|
n_prec = len(digits) + d_idx
|
|
|
|
|
2009-12-22 23:18:51 +08:00
|
|
|
# If we have more than the maximum digits allowed, then throw an
|
2008-08-06 02:13:06 +08:00
|
|
|
# InvalidDecimal exception.
|
|
|
|
if n_prec > max_prec:
|
2014-09-04 20:15:09 +08:00
|
|
|
raise InvalidDecimal(
|
|
|
|
'A DecimalField with max_digits %d, decimal_places %d must '
|
|
|
|
'round to an absolute value less than 10^%d.' %
|
|
|
|
(model_field.max_digits, model_field.decimal_places, max_prec)
|
|
|
|
)
|
2008-08-06 02:13:06 +08:00
|
|
|
val = d
|
|
|
|
elif isinstance(ogr_field, (OFTReal, OFTString)) and isinstance(model_field, models.IntegerField):
|
|
|
|
# Attempt to convert any OFTReal and OFTString value to an OFTInteger.
|
|
|
|
try:
|
|
|
|
val = int(ogr_field.value)
|
2013-09-30 23:55:14 +08:00
|
|
|
except ValueError:
|
2008-08-06 02:13:06 +08:00
|
|
|
raise InvalidInteger('Could not construct integer from: %s' % ogr_field.value)
|
|
|
|
else:
|
|
|
|
val = ogr_field.value
|
|
|
|
return val
|
|
|
|
|
|
|
|
def verify_fk(self, feat, rel_model, rel_mapping):
|
|
|
|
"""
|
|
|
|
Given an OGR Feature, the related model and its dictionary mapping,
|
2017-01-25 04:31:57 +08:00
|
|
|
retrieve the related model for the ForeignKey mapping.
|
2008-08-06 02:13:06 +08:00
|
|
|
"""
|
|
|
|
# TODO: It is expensive to retrieve a model for every record --
|
2009-12-22 23:18:51 +08:00
|
|
|
# explore if an efficient mechanism exists for caching related
|
2008-08-06 02:13:06 +08:00
|
|
|
# ForeignKey models.
|
|
|
|
|
|
|
|
# Constructing and verifying the related model keyword arguments.
|
|
|
|
fk_kwargs = {}
|
|
|
|
for field_name, ogr_name in rel_mapping.items():
|
|
|
|
fk_kwargs[field_name] = self.verify_ogr_field(feat[ogr_name], rel_model._meta.get_field(field_name))
|
|
|
|
|
|
|
|
# Attempting to retrieve and return the related model.
|
|
|
|
try:
|
2011-09-11 01:19:05 +08:00
|
|
|
return rel_model.objects.using(self.using).get(**fk_kwargs)
|
2008-08-06 02:13:06 +08:00
|
|
|
except ObjectDoesNotExist:
|
2014-09-04 20:15:09 +08:00
|
|
|
raise MissingForeignKey(
|
|
|
|
'No ForeignKey %s model found with keyword arguments: %s' %
|
|
|
|
(rel_model.__name__, fk_kwargs)
|
|
|
|
)
|
2009-12-22 23:18:51 +08:00
|
|
|
|
2008-08-06 02:13:06 +08:00
|
|
|
def verify_geom(self, geom, model_field):
|
|
|
|
"""
|
2017-01-25 04:31:57 +08:00
|
|
|
Verify the geometry -- construct and return a GeometryCollection
|
2008-08-06 02:13:06 +08:00
|
|
|
if necessary (for example if the model field is MultiPolygonField while
|
|
|
|
the mapped shapefile only contains Polygons).
|
|
|
|
"""
|
2009-11-17 02:49:00 +08:00
|
|
|
# Downgrade a 3D geom to a 2D one, if necessary.
|
|
|
|
if self.coord_dim != geom.coord_dim:
|
|
|
|
geom.coord_dim = self.coord_dim
|
|
|
|
|
2008-08-06 02:13:06 +08:00
|
|
|
if self.make_multi(geom.geom_type, model_field):
|
|
|
|
# Constructing a multi-geometry type to contain the single geometry
|
|
|
|
multi_type = self.MULTI_TYPES[geom.geom_type.num]
|
|
|
|
g = OGRGeometry(multi_type)
|
|
|
|
g.add(geom)
|
|
|
|
else:
|
|
|
|
g = geom
|
|
|
|
|
|
|
|
# Transforming the geometry with our Coordinate Transformation object,
|
2009-12-22 23:18:51 +08:00
|
|
|
# but only if the class variable `transform` is set w/a CoordTransform
|
2008-08-06 02:13:06 +08:00
|
|
|
# object.
|
2013-10-17 16:17:41 +08:00
|
|
|
if self.transform:
|
|
|
|
g.transform(self.transform)
|
2009-12-22 23:18:51 +08:00
|
|
|
|
2008-08-06 02:13:06 +08:00
|
|
|
# Returning the WKT of the geometry.
|
|
|
|
return g.wkt
|
|
|
|
|
2015-02-06 02:25:34 +08:00
|
|
|
# #### Other model methods ####
|
2008-08-06 02:13:06 +08:00
|
|
|
def coord_transform(self):
|
2017-01-25 04:31:57 +08:00
|
|
|
"Return the coordinate transformation object."
|
2009-12-22 23:18:51 +08:00
|
|
|
SpatialRefSys = self.spatial_backend.spatial_ref_sys()
|
2008-08-06 02:13:06 +08:00
|
|
|
try:
|
|
|
|
# Getting the target spatial reference system
|
2011-09-11 01:19:05 +08:00
|
|
|
target_srs = SpatialRefSys.objects.using(self.using).get(srid=self.geo_field.srid).srs
|
2008-08-06 02:13:06 +08:00
|
|
|
|
|
|
|
# Creating the CoordTransform object
|
|
|
|
return CoordTransform(self.source_srs, target_srs)
|
2017-01-08 03:13:29 +08:00
|
|
|
except Exception as exc:
|
|
|
|
raise LayerMapError(
|
|
|
|
'Could not translate between the data source and model geometry.'
|
|
|
|
) from exc
|
2008-08-06 02:13:06 +08:00
|
|
|
|
2009-12-25 22:37:57 +08:00
|
|
|
def geometry_field(self):
|
2017-01-25 04:31:57 +08:00
|
|
|
"Return the GeometryField instance associated with the geographic column."
|
2015-01-07 08:16:35 +08:00
|
|
|
# Use `get_field()` on the model's options so that we
|
2009-12-25 22:37:57 +08:00
|
|
|
# get the correct field instance if there's model inheritance.
|
2009-11-02 10:17:56 +08:00
|
|
|
opts = self.model._meta
|
2015-01-07 08:16:35 +08:00
|
|
|
return opts.get_field(self.geom_field)
|
2008-08-06 02:13:06 +08:00
|
|
|
|
|
|
|
def make_multi(self, geom_type, model_field):
|
|
|
|
"""
|
2009-12-22 23:18:51 +08:00
|
|
|
Given the OGRGeomType for a geometry and its associated GeometryField,
|
2008-08-06 02:13:06 +08:00
|
|
|
determine whether the geometry should be turned into a GeometryCollection.
|
|
|
|
"""
|
2009-12-22 23:18:51 +08:00
|
|
|
return (geom_type.num in self.MULTI_TYPES and
|
2008-08-06 02:13:06 +08:00
|
|
|
model_field.__class__.__name__ == 'Multi%s' % geom_type.django)
|
|
|
|
|
2009-12-22 23:18:51 +08:00
|
|
|
def save(self, verbose=False, fid_range=False, step=False,
|
2008-08-06 02:13:06 +08:00
|
|
|
progress=False, silent=False, stream=sys.stdout, strict=False):
|
|
|
|
"""
|
2017-01-25 04:31:57 +08:00
|
|
|
Save the contents from the OGR DataSource Layer into the database
|
2009-12-22 23:18:51 +08:00
|
|
|
according to the mapping dictionary given at initialization.
|
|
|
|
|
2008-08-06 02:13:06 +08:00
|
|
|
Keyword Parameters:
|
|
|
|
verbose:
|
2009-12-22 23:18:51 +08:00
|
|
|
If set, information will be printed subsequent to each model save
|
2008-08-06 02:13:06 +08:00
|
|
|
executed on the database.
|
|
|
|
|
|
|
|
fid_range:
|
|
|
|
May be set with a slice or tuple of (begin, end) feature ID's to map
|
|
|
|
from the data source. In other words, this keyword enables the user
|
|
|
|
to selectively import a subset range of features in the geographic
|
|
|
|
data source.
|
|
|
|
|
|
|
|
step:
|
2009-12-22 23:18:51 +08:00
|
|
|
If set with an integer, transactions will occur at every step
|
|
|
|
interval. For example, if step=1000, a commit would occur after
|
2008-08-06 02:13:06 +08:00
|
|
|
the 1,000th feature, the 2,000th feature etc.
|
|
|
|
|
|
|
|
progress:
|
2009-12-22 23:18:51 +08:00
|
|
|
When this keyword is set, status information will be printed giving
|
2014-03-02 22:25:53 +08:00
|
|
|
the number of features processed and successfully saved. By default,
|
2009-12-22 23:18:51 +08:00
|
|
|
progress information will pe printed every 1000 features processed,
|
|
|
|
however, this default may be overridden by setting this keyword with an
|
2008-08-06 02:13:06 +08:00
|
|
|
integer for the desired interval.
|
|
|
|
|
|
|
|
stream:
|
2009-12-22 23:18:51 +08:00
|
|
|
Status information will be written to this file handle. Defaults to
|
2008-08-06 02:13:06 +08:00
|
|
|
using `sys.stdout`, but any object with a `write` method is supported.
|
|
|
|
|
|
|
|
silent:
|
2009-12-22 23:18:51 +08:00
|
|
|
By default, non-fatal error notifications are printed to stdout, but
|
2008-08-06 02:13:06 +08:00
|
|
|
this keyword may be set to disable these notifications.
|
|
|
|
|
|
|
|
strict:
|
2009-12-22 23:18:51 +08:00
|
|
|
Execution of the model mapping will cease upon the first error
|
2008-08-06 02:13:06 +08:00
|
|
|
encountered. The default behavior is to attempt to continue.
|
|
|
|
"""
|
|
|
|
# Getting the default Feature ID range.
|
|
|
|
default_range = self.check_fid_range(fid_range)
|
2009-12-22 23:18:51 +08:00
|
|
|
|
2008-08-06 02:13:06 +08:00
|
|
|
# Setting the progress interval, if requested.
|
|
|
|
if progress:
|
|
|
|
if progress is True or not isinstance(progress, int):
|
|
|
|
progress_interval = 1000
|
|
|
|
else:
|
|
|
|
progress_interval = progress
|
|
|
|
|
|
|
|
def _save(feat_range=default_range, num_feat=0, num_saved=0):
|
|
|
|
if feat_range:
|
|
|
|
layer_iter = self.layer[feat_range]
|
|
|
|
else:
|
|
|
|
layer_iter = self.layer
|
|
|
|
|
|
|
|
for feat in layer_iter:
|
|
|
|
num_feat += 1
|
|
|
|
# Getting the keyword arguments
|
|
|
|
try:
|
|
|
|
kwargs = self.feature_kwargs(feat)
|
2012-04-29 00:09:37 +08:00
|
|
|
except LayerMapError as msg:
|
2008-08-06 02:13:06 +08:00
|
|
|
# Something borked the validation
|
2013-10-17 16:17:41 +08:00
|
|
|
if strict:
|
|
|
|
raise
|
2009-12-22 23:18:51 +08:00
|
|
|
elif not silent:
|
2008-08-06 02:13:06 +08:00
|
|
|
stream.write('Ignoring Feature ID %s because: %s\n' % (feat.fid, msg))
|
|
|
|
else:
|
|
|
|
# Constructing the model using the keyword args
|
|
|
|
is_update = False
|
|
|
|
if self.unique:
|
|
|
|
# If we want unique models on a particular field, handle the
|
|
|
|
# geometry appropriately.
|
|
|
|
try:
|
|
|
|
# Getting the keyword arguments and retrieving
|
|
|
|
# the unique model.
|
|
|
|
u_kwargs = self.unique_kwargs(kwargs)
|
2009-12-22 23:18:51 +08:00
|
|
|
m = self.model.objects.using(self.using).get(**u_kwargs)
|
2008-08-06 02:13:06 +08:00
|
|
|
is_update = True
|
2009-12-22 23:18:51 +08:00
|
|
|
|
|
|
|
# Getting the geometry (in OGR form), creating
|
|
|
|
# one from the kwargs WKT, adding in additional
|
|
|
|
# geometries, and update the attribute with the
|
2008-08-06 02:13:06 +08:00
|
|
|
# just-updated geometry WKT.
|
2018-06-19 20:21:39 +08:00
|
|
|
geom_value = getattr(m, self.geom_field)
|
|
|
|
if geom_value is None:
|
|
|
|
geom = OGRGeometry(kwargs[self.geom_field])
|
|
|
|
else:
|
|
|
|
geom = geom_value.ogr
|
|
|
|
new = OGRGeometry(kwargs[self.geom_field])
|
|
|
|
for g in new:
|
|
|
|
geom.add(g)
|
2008-08-06 02:13:06 +08:00
|
|
|
setattr(m, self.geom_field, geom.wkt)
|
|
|
|
except ObjectDoesNotExist:
|
|
|
|
# No unique model exists yet, create.
|
|
|
|
m = self.model(**kwargs)
|
|
|
|
else:
|
|
|
|
m = self.model(**kwargs)
|
|
|
|
|
|
|
|
try:
|
|
|
|
# Attempting to save.
|
2009-12-22 23:18:51 +08:00
|
|
|
m.save(using=self.using)
|
2008-08-06 02:13:06 +08:00
|
|
|
num_saved += 1
|
2013-10-17 16:17:41 +08:00
|
|
|
if verbose:
|
|
|
|
stream.write('%s: %s\n' % ('Updated' if is_update else 'Saved', m))
|
2012-04-29 00:09:37 +08:00
|
|
|
except Exception as msg:
|
2009-12-22 23:18:51 +08:00
|
|
|
if strict:
|
2008-08-06 02:13:06 +08:00
|
|
|
# Bailing out if the `strict` keyword is set.
|
|
|
|
if not silent:
|
2014-09-04 20:15:09 +08:00
|
|
|
stream.write(
|
|
|
|
'Failed to save the feature (id: %s) into the '
|
|
|
|
'model with the keyword arguments:\n' % feat.fid
|
|
|
|
)
|
2008-08-06 02:13:06 +08:00
|
|
|
stream.write('%s\n' % kwargs)
|
|
|
|
raise
|
|
|
|
elif not silent:
|
|
|
|
stream.write('Failed to save %s:\n %s\nContinuing\n' % (kwargs, msg))
|
|
|
|
|
|
|
|
# Printing progress information, if requested.
|
|
|
|
if progress and num_feat % progress_interval == 0:
|
2019-02-14 02:59:44 +08:00
|
|
|
stream.write('Processed %d features, saved %d ...\n' % (num_feat, num_saved))
|
2009-12-22 23:18:51 +08:00
|
|
|
|
2008-08-06 02:13:06 +08:00
|
|
|
# Only used for status output purposes -- incremental saving uses the
|
|
|
|
# values returned here.
|
|
|
|
return num_saved, num_feat
|
|
|
|
|
2013-03-12 03:03:17 +08:00
|
|
|
if self.transaction_decorator is not None:
|
|
|
|
_save = self.transaction_decorator(_save)
|
|
|
|
|
2008-08-06 02:13:06 +08:00
|
|
|
nfeat = self.layer.num_feat
|
|
|
|
if step and isinstance(step, int) and step < nfeat:
|
2009-12-22 23:18:51 +08:00
|
|
|
# Incremental saving is requested at the given interval (step)
|
|
|
|
if default_range:
|
2008-08-06 02:13:06 +08:00
|
|
|
raise LayerMapError('The `step` keyword may not be used in conjunction with the `fid_range` keyword.')
|
|
|
|
beg, num_feat, num_saved = (0, 0, 0)
|
|
|
|
indices = range(step, nfeat, step)
|
|
|
|
n_i = len(indices)
|
|
|
|
|
|
|
|
for i, end in enumerate(indices):
|
|
|
|
# Constructing the slice to use for this step; the last slice is
|
|
|
|
# special (e.g, [100:] instead of [90:100]).
|
2013-11-04 02:08:55 +08:00
|
|
|
if i + 1 == n_i:
|
2013-10-17 16:17:41 +08:00
|
|
|
step_slice = slice(beg, None)
|
|
|
|
else:
|
|
|
|
step_slice = slice(beg, end)
|
2009-12-22 23:18:51 +08:00
|
|
|
|
2008-08-06 02:13:06 +08:00
|
|
|
try:
|
|
|
|
num_feat, num_saved = _save(step_slice, num_feat, num_saved)
|
|
|
|
beg = end
|
2015-11-16 02:52:47 +08:00
|
|
|
except Exception: # Deliberately catch everything
|
2008-08-06 02:13:06 +08:00
|
|
|
stream.write('%s\nFailed to save slice: %s\n' % ('=-' * 20, step_slice))
|
|
|
|
raise
|
|
|
|
else:
|
|
|
|
# Otherwise, just calling the previously defined _save() function.
|
|
|
|
_save()
|