diff --git a/tracking/management/commands/import_gpx.py b/tracking/management/commands/import_gpx.py index bf91039..1eeef3f 100644 --- a/tracking/management/commands/import_gpx.py +++ b/tracking/management/commands/import_gpx.py @@ -33,4 +33,5 @@ class Command(BaseCommand): gpx = dict(xmltodict.parse(fd.read()))['gpx'] user = self.user - Track.objects.create_from_gpx(gpx, user) + created, track = Track.objects.get_or_create_from_gpx(gpx, user) + print track diff --git a/tracking/models.py b/tracking/models.py index 6427950..1c113a9 100644 --- a/tracking/models.py +++ b/tracking/models.py @@ -7,7 +7,7 @@ from django.contrib.auth.models import User class TrackManager(models.Manager): - def create_from_gpx(cls, obj, user): + def get_or_create_from_gpx(cls, obj, user): # Get some Meta data from the gpx file. metadata = obj['metadata'] start_time = metadata['time'] @@ -15,24 +15,28 @@ class TrackManager(models.Manager): tracks = obj['trk'] name = tracks['name'] segments = tracks['trkseg'] - # Check unimplemented features - with transaction.atomic(): - track = Track.objects.create(user=user, - start=start_time, - name=name) - points = segments['trkpt'] - segment = Segment(track=track, time=points[0]['time']) - segment.save() - for pt in points: - lat, lon = float(pt['@lat']), float(pt['@lon']) - poly_pt = geos.Point(lon, lat) - Point.objects.create(segment=segment, - time=pt['time'], - elevation=pt['ele'], - point=poly_pt) - return track - raise Exception("Track not created, rolling back DB") + track, created = cls.model.objects.get_or_create( + user=user, + start=start_time, + name=name) + if created: + with transaction.atomic(): + points = segments['trkpt'] + segment = Segment( + track=track, + time=points[0]['time']) + segment.save() + for pt in points: + lon = float(pt['@lon']) + lat = float(pt['@lat']) + + Point.objects.create( + segment=segment, + time=pt['time'], + elevation=pt['ele'], + point=geos.Point(lon, lat)) + return created, track class Track(models.Model):