4

I'm using GeoDjango's LayerMapping utility to try and import a set of features. The catch is that aside from the attributes in the source layer, I want all the destination features to have the same value of another attribute. Specifically:

> sourceLayer = theDataSource[5]
> sourceLayer.fields
['DataSources_ID', 'Source', 'Notes', 'Shape']
> from django.contrib.gis.utils import mapping
> fieldMapping = mapping(theDataSource, layer_key=5)
{'datasources_id': 'DataSources_ID', 'source': 'Source', 'notes': 'Notes', 'shape': 'MULTIPOLYGON' }

The destination model has another field, 'owningmap', which is an integer field. I would like to load data from the OGR source via...

> lm = LayerMapping(DestinationModel, theDataSource, fieldMapping, layer=5)
> lm.save()

... but I would like every feature to have the same integer value put in to the 'owningmap' field. As though I could somehow add a "static" mapping to fieldMapping...

> fieldMapping['owningmap'] = 2

Is this possible? Otherwise my last resort is to load via LayerMapping, then calculate the value for all the just-loaded features in a separate database transaction...

Thanks!

1 Answer 1

10

It's been a long time since this question was asked but geodjango answers are few and far between. For anyone else searching for something like this, you can subclass LayerMapping and add the same set of static fields to every feature like this:

class CustomLayerMapping(LayerMapping):
    def __init__(self, *args, **kwargs):
        self.custom = kwargs.pop('custom', {})
        super(CustomLayerMapping, self).__init__(*args, **kwargs)

    def feature_kwargs(self, feature):
        kwargs = super(CustomLayerMapping, self).feature_kwargs(feature)
        kwargs.update(self.custom)
        return kwargs

layer_map = CustomLayerMapping(
    model = YourModel,
    data = 'path/to/datasource',
    mapping = {
        'fips_code': 'STATEFP',
        'name': 'NAME',
        'shape': 'MULTIPOLYGON'
    },
    custom = {
        'my_static_field': my_static_value
    }
)

layer_map.save(verbose = True, strict = True)
1
  • 1
    Nice answer. It is useful whenever you want to record the import batch a feature came from which is probably most of the time - arguably a function like this warrants inclusion in LayerMapping.
    – Alexander
    Commented Oct 9, 2018 at 15:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.