当我使用geojson序列化对象时,我需要添加一个包含反向外键的字段。
我使用Django 1.9并拥有以下模型:
class NaturalEarthProvince(models.Model):
adm1_code = models.CharField(max_length=10, primary_key=True)
name = models.CharField(max_length=100)
geom = models.MultiPolygonField(srid=4326)
objects = models.GeoManager()
class NaturalEarthMerged(models.Model):
basicname = models.CharField(max_length=200, blank=True)
fkprovince = models.OneToOneField(NaturalEarthProvince, blank=True, null=True)
fktouristicarea = models.ForeignKey(TouristicArea, blank=True, null=True, related_name='relatednatmerged', on_delete=models.SET_NULL)
class TouristicArea(models.Model):
areaname = models.CharField(max_length=200, blank=True)
fkcountry = models.ForeignKey(NaturalEarthCountry, blank=True, null=True)
我想做的是:
location = NaturalEarthProvince.objects.filter(adm0_a3=code)
locationserialized = serialize('geojson', location, geometry_field='geom', fields=('name', 'adm1_cod_1', 'touristicarea')
旅游区是location.naturalearthmerged.fktouristicarea
有任何线索吗?
答案 0 :(得分:0)
我设法解决此问题的唯一方法是手动将此特定字段添加到json对象:
locationserialized = serialize('geojson', location, geometry_field='geom', fields=('name', 'adm1_cod_1', 'adm0_a3'))
resp_obj = json.loads(locationserialized)
i = 0
for eachobj in resp_obj['features']:
try:
resp_obj['features'][i]['properties']['touristicarea'] = NaturalEarthMerged.objects.filter(fkprovince__adm1_cod_1=eachobj['properties']['adm1_cod_1'])[0].fktouristicarea.id
except:
resp_obj['features'][i]['properties']['touristicarea'] = 0
i = i+1
return JsonResponse(resp_obj)