2

I've been using GeoDjango for a few months now without any issues however when importing a new shape file the id number is being saved instead of the gridcode. The gridcode field has an int that is valuable to my project.

I know the gridcode field is present in the shapefile because I can test it in the shell.

#shell
>>> print(lyr.fields)
['Id', 'gridcode']
>>> feat = lyr[234]
>>> print(feat.get('gridcode'))
90 #This is the desired value 

Ive set up my model the same way I always do:

#models.py
class GeoModel(models.Model):
    idn = geomodels.BigIntegerField(null=True)
    grd = geomodels.BigIntegerField(null=True)
    geo = geomodels.MultiPolygonField(null=True, srid=4326)

    def __int__(self):
        return self.grd

path_shp = os.path.abspath(os.path.join(os.path.dirname(app.__file__), 'data', 'folder', 'map.shp'))

mapping = {
    'idn': 'Id',
    'grd': 'gridcode',
    'geo': 'MULTIPOLYGON',}

def run(verbose=True):
    lm = LayerMapping(GeoModel, path_shp, mapping, transform=False)  
    lm.save(strict=True, verbose=verbose) 

However when I try to store the data it stores the id number instead of the gridcode. For example, the terminal looks like this:

Saved: GeoModel object (1517)
Saved: GeoModel object (1518)
Saved: GeoModel object (1519)
Saved: GeoModel object (1520)
[ . . .]

Any help would be much appreciated

Display name
  • 753
  • 10
  • 28
  • is the gridcode not being saved at all or is it that it is just not displaying when you save it? You may just need to set the __str__ method on your model – leelum1 Aug 05 '20 at 14:30
  • I don't think its being saved at all, I haven't been able to pull any value other than the value saved as "self" for each of my Geodjango functions. I tried changing _int_ to str in the self definition and it unsurprisingly gave me a type error : TypeError: __str__ returned non-string (type int). @leelum1 – Display name Aug 05 '20 at 22:42

1 Answers1

2

I found a simple workaround. After digging around in the GeoDjango docs under "Lazy Geometries", I found I can just query values that aren't returned by "intersects". For example: When I run

>>> q = GeoModel.objects.get(geo__intersects=point)
# and then I get a value I don't care for (i.e GeoModel object (1520))
# I can then run the following:
>>> q.grd
# and return the following:
90

Although this doesn't directly solve the problem above, it makes the problem irrelevant to me and likely to anyone else facing the same problem in the future.

Display name
  • 753
  • 10
  • 28