簡體   English   中英

自定義字段 Django Rest Framework

[英]Custom field Django Rest Framework

我正在處理一個位置項目,對於后端,我正在使用帶有 PostgreSQL 的 Django Rest 框架。我以以下格式獲取請求對象。

{"BatchId": 1, "GeoLocation": [{"latitude": 28.257999420166016, "longitude": 77.6415388}, {"latitude": 12.9562821, "longitude": 77.6415199}]}

我想將 GeoLocation 存儲在字符串字段中,因此我使用 ($) 進行數組元素分隔。 例如:-

28.257999420166016**$**77.6415388

我為此創建了一個自定義字段,但它顯示無效錯誤。

模型.py

class GeoLocation(models.Model):

    date = models.DateField()
    location = ArrayField(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

或者有沒有其他存儲方式?

作為建議,您可以將其保留為 json 對象。 PostgreSQL 特定模型字段JSONField

序列化器:

    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]

模型:

    class GeoLocation(models.Model):
       date = models.DateField()
       location = JSONField()

使用 Json 字段

序列化器.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']

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM