Search code examples
pythondjangoserializationgeojson

Include a Foreign Key in the Django GeoJSON serializer


When I serialize an object with geojson, I would need to add a field containing a reverse Foreign Key.

I use Django 1.9 and have the following models:

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)

What I would like to do is:

location = NaturalEarthProvince.objects.filter(adm0_a3=code)
locationserialized = serialize('geojson', location, geometry_field='geom', fields=('name', 'adm1_cod_1', 'touristicarea')

with touristicarea being location.naturalearthmerged.fktouristicarea

Any clue?


Solution

  • The only way I managed to solve this issue is by adding this specific field manually to the json object:

    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)