简体   繁体   中英

Custom field Django Rest Framework

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 ?

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()

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='+')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM