Django Rest 框架 GeoDjango 序列化程序

Django Rest Framework GeoDjango Serializers

有没有一种方法可以使用用户模型创建一个序列化程序来显示存储在该用户下的位置?

我可以创建常规位置序列化器,但是,我希望能够创建如下所示的 url: 本地主机。com/api/users/username-goes-here/location

在此页面上,我希望它显示该特定用户的所有位置。

models.py

class Location(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    location = models.PointField(srid=4326)

serializers.py

class UserTestSerializer(serializers.ModelSerializer):
    location = serializers.PointField(source='location.location')
    class Meta:
        model = User
        fields = ('id', 'username', 'location')

The error I get is: AttributeError: module 'rest_framework.serializers' has no attribute 'PointField'

谢谢!

rest 框架不附带默认的序列化器点字段来支持几何字段。

请检查下面的库。

https://github.com/openwisp/django-rest-framework-gis

或者您可以创建自定义序列化器字段

from rest_framework_gis.serializers import GeometryField


class GeometryPointFieldSerializerFields(GeometryField):

    def to_internal_value(self, value):
        try:
            value = value.split(",")
        except:
            raise ValidationError(
                _("Enter the co-ordinates in (latitude,longitude). Ex-12,13")
            )
        try:
            latitude = float(value[0])
        except ValueError:
            raise ValidationError(
                _("Enter the co-ordinates in (latitude,longitude). Ex-12,13")
            )
        try:
            longitude = float(value[1])
        except ValueError:
            raise ValidationError(
                _("Enter the co-ordinates in (latitude,longitude). Ex-12,13")
            )
        value = {
            "type": "Point",
            "coordinates": [longitude, latitude]
        }
        value = json.dumps(value)
        try:
            return GEOSGeometry(value)
        except (ValueError, GEOSException, OGRException, TypeError):
            raise ValidationError(
                _('Invalid format: string or unicode input unrecognized as GeoJSON, WKT EWKT or HEXEWKB.'))

    def to_representation(self, value):
        """ """
        value = super(
            GeometryPointFieldSerializerFields, self).to_representation(value)
        # change to compatible with google map
        data = {
            "type": "Point",
            "coordinates": [
                value['coordinates'][1], value['coordinates'][0]
            ]
        }
        return data

在序列化器中你可以使用上面的字段

class UserTestSerializer(serializers.ModelSerializer):
    location = GeometryPointFieldSerializerFields(source='location.location')
    class Meta:
        model = User
        fields = ('id', 'username', 'location')