I have two models and need to serialize Article
as Geojson by setting the geo_field
attribute as point
from the Location
model. After following the solution given here I get the error:
Got AttributeError when attempting to get a value for field `point` on serializer `ArticleSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `Article` instance.
Original exception text was: 'ManyRelatedManager' object has no attribute 'point'.
Here are my models:
class Location(models.Model):
city = models.CharField(max_length=200)
point = models.PointField(srid=4326)
objects = models.GeoManager()
class Article(models.Model):
locations = models.ManyToManyField(Location)
article_title = models.CharField(max_length=200)
@property
def point(self):
return self.locations.point
And my serializer:
class ArticleSerializer(GeoFeatureModelSerializer):
point = GeometryField()
class Meta:
model = Article
geo_field = "point"
id_field = False
fields = ('pub_date', 'point',)
Any help appreciated. I've been trying to find a solution to this for ages with little success!
UPDATE!
Ok, getting somewhere with this. I created a LocationSerializer
and reference this in ArticleSerializer
. These now look something like this:
class LocationSerializer(serializers.ModelSerializer):
class Meta:
model = Location
geo_field = "point"
id_field = False
fields = ('point',)
class ArticleSerializer(GeoFeatureModelSerializer):
locations = LocationSerializer(many=True)
class Meta:
model = Article
geo_field = "locations"
id_field = False
fields = ('pub_date', 'locations',)
The output is closer to what I want...but still a bit obscure in construct:
{
"type":"FeatureCollection",
"features":[
{
"type":"Feature",
"geometry":[
{
"point":{
"type":"Point",
"coordinates":[
-2.200337956118645,
53.48316423741371
]
}
},
{
"point":{
"type":"Point",
"coordinates":[
0.041198730463564,
51.51002453017606
]
}
}
],
"properties":{
"pub_date":"2015-04-06T20:38:59Z"
}
}
]
}
UPDATE!
The format I require is:
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"time": "2013-01-22 08:42:26+01"
},
"geometry": {
"type": "Point",
"coordinates": [
7.582512743,
51.933292258,
1
]
}
},