0

I have a GeoDjango model like below (in "data" app):

from django.contrib.gis.db import models

class FirstModel(models.Model):
    data_id = models.IntegerField(blank=True, null=True)
    model_base_date = models.DateTimeField(blank=True, null=True)
    mpoly = models.MultiPolygonField(blank=True, null=True)

    class Meta:
        db_table = "first_model"

Here is how I used this model in LayerMapping class to import a test shapefile into my PostGIS database:

from django.contrib.gis.utils import LayerMapping
from data.models import FirstModel
from datetime import datetime

mapping = {
    'mpoly' : 'MULTIPOLYGON',

}


world_shp = 'po/my_shapefile.shp'

lm = LayerMapping(FirstModel, world_shp, mapping, transform=False, )
lm.save(strict=True, )  

After running the code above, I look inside the table in the database, and all of the model_base_date and data_id fields are empty. Here is a picture from the table:enter image description here How can I add the model_base_date and data_id when importing the shapefile into the table?

1 Answer 1

1

I am not super familiar with django and LayerMapping.

But if you look in the doc here : https://docs.djangoproject.com/fr/3.1/ref/contrib/gis/layermapping/, mapping is actually a dictionary that match your shapefield fields with your model fields.

So you may need to add it in your mapping dictionary this way :

{ 
'mpoly' : multipolygon,
'model_base_date' : 'shapefile_field_date',
'data_id' : 'shapefile_field_data_id'
}

Using the shapefile field's name in this dictionary.

5
  • So you mean that I have to get these values (model_base_date and data_id) from the input shapefile?
    – Muser
    Commented Dec 17, 2020 at 8:30
  • If you have values in your shapefile. If you don't, then you should try to add the values in the database. Commented Dec 17, 2020 at 8:42
  • If you want default values in your database, you can run a query like this one : "" "update "tablename_in_db" set data_id="your_value", model_base_data="your_value" "". Commented Dec 17, 2020 at 8:49
  • Actually I do not want a default value. And that is because each shapefile has its own model_base_date and data_id valaues. So, I think that, as you stated, I have to add 2 fields in the shapefile
    – Muser
    Commented Dec 17, 2020 at 9:01
  • It worked. Thank you
    – Muser
    Commented Dec 17, 2020 at 10:18

This site is temporarily in read-only mode and not accepting new answers.

Not the answer you're looking for? Browse other questions tagged .