Tuesday, 30 July 2019

Parsing fields in django-import-export before importing

I am using django-import-export package to expect a csv file containing a location's name and its longitude and latitude.

I want to parse the longitude and latitude field from the csv to convert them into django.contrib.gis.geos.Point object so that I can input it to my Location model's geom field.

# models.py
from django.contrib.gis.db import models
class Location(models.Model):
    name = models.CharField(max_length=200)
    geom = models.PointField(null=True, blank=True)

    def __str__(self):
        return self.name

# admin.py
from .models import Location
from import_export import resources
from import_export.admin import ImportExportModelAdmin

class LocationResource(resources.ModelResource):
    geom = Field()
    latitude = Field()
    longitude = Field()

    class Meta:
        model = Location
        fields = ('id','name', 'latitude', 'longitude')
        exclude = ('geom')
        export_order = ('id', 'name', 'latitude', 'longitude')

    def dehydrate_geom(self, data):
        return Point(data.longitude, data.longitude)

class LocationAdmin(ImportExportModelAdmin):
    resource_class = LocationResource

admin.site.register(Location, LocationAdmin)

This is how far I got but to no success. Must have:

Location(name='name', geom=Point(longitude, latitude))

CSV file: locations.csv

id,name,longitude,latitude
1,Naga,120.18,18.20



from Parsing fields in django-import-export before importing

No comments:

Post a Comment