我试图得到一个Json响应,其中包含地理位置和Django中外键对象的信息。
我当前的代码如下:
location_point = Point(location.longitude, location.latitude, srid=4326)
events = TimetableEvent.objects.annotate(distance=Distance('venue__location', location_point)).order_by('distance')[0:5].values('activity__name','venue__name','venue__location','distance')
qs_json = serializers.serialize('geojson', events,geometry_field='point')
这在尝试使用值查询集时给了我一个元错误
*** AttributeError: 'dict' object has no attribute '_meta'
我也尝试过使用geojson字段选择点,但是我没有运气:
location_point = Point(location.longitude, location.latitude, srid=4326)
events = TimetableEvent.objects.annotate(distance=Distance('venue__location', location_point)).order_by('distance')[0:5]
qs_json = serializers.serialize('geojson', events,geometry_field='venue__location',fields=('activity__name','venue__name','venue__location','distance',))
这只是给我空数据
p qs_json
'{"type": "FeatureCollection", "crs": {"type": "name", "properties": {"name": "EPSG:4326"}}, "features": [{"type": "Feature", "properties": {}, "geometry": null}, {"type": "Feature", "properties": {}, "geometry": null}, {"type": "Feature", "properties": {}, "geometry": null}, {"type": "Feature", "properties": {}, "geometry": null}]}'
然后我尝试使用json转储打印出数据列表,但出现与距离注释或点有关的错误,例如:
(Pdb) json.dumps(list(events))
*** TypeError: Object of type 'Point' is not JSON serializable
有几种方法可以做到,但是我真的很感谢能以正确的方式获得帮助!
时间表事件的模型是:
class TimetableEvent(models.Model):
activity = models.ForeignKey(Activity, on_delete=models.DO_NOTHING,)
venue = models.ForeignKey(Venue,on_delete=models.DO_NOTHING,)
start_time = models.TimeField()
end_time =models.TimeField()
date = models.DateTimeField('event date')
def __str__(self):
return self.activity.name +' at '+ self.venue.name