Reputation: 279
I am working on a location project and for backend i am using Django Rest framework with PostgreSQL.I am getting the request object in following format.
{"BatchId": 1, "GeoLocation": [{"latitude": 28.257999420166016, "longitude": 77.6415388}, {"latitude": 12.9562821, "longitude": 77.6415199}]}
I want to store GeoLocation in a string field so i am using ($) for array elements separation. for example:-
28.257999420166016**$**77.6415388
i have create a custom field for the this but it showing invalidation error.
model.py
class GeoLocation(models.Model):
date = models.DateField()
location = ArrayField(GeoLocationField())
GeoLocationField
class GeoLocationField(models.Field):
def from_db_value(self, value, expression, connection):
if value is None:
return value
return parse_location(value)
def get_prep_value(self, value):
return '$'.join([''.join(l) for l in (value.latitude,value.longitude)])
def parse_location(point_string):
args = point_string.split('$')
if len(args) != 2:
raise ValidationError(_("Invalid input for a Location instance"))
return Location(*args)
class Location:
def __init__(self, latitude, longitude):
self.latitude = latitude
self.longitude = longitude
or is there any other way to store ?
Upvotes: 1
Views: 1337
Reputation: 363
As a suggesstion, you can keep it as a json object. PostgreSQL specific model fields JSONField
serializers:
class LocationSerializer(serializers.Serializer):
latitude = serializers.FloatField(read_only=True)
longitude = serializers.FloatField(read_only=True)
class GeoLocationSerializer(serializers.ModelSerializer):
location = LocationSerializer(many=True)
class Meta:
model = GeoLocation
fields = [date, location]
model:
class GeoLocation(models.Model):
date = models.DateField()
location = JSONField()
Upvotes: 1
Reputation: 279
Using Json Field
Serializer.py
class JSONSerializerField(serializers.Field):
""" Serializer for JSONField -- required to make field writable"""
def to_internal_value(self, data):
return data
def to_representation(self, value):
return value
class GeoLocationSerializer(serializers.ModelSerializer):
location = JSONSerializerField()
class Meta:
model = models.GeoLocation
fields = ['id', 'location', 'date']
Model.py
class GeoLocation(models.Model):
date = models.DateField(default=datetime.date.today)
location = JSONField()
entered_user = models.ForeignKey(User, on_delete=models.PROTECT, related_name='+')
Upvotes: 0