How to add ManyToMany field in geojson serializer

19 Views Asked by At

After loading geospatial data into postgresql + postgis database, the goal is to return it in a view as geojson format.

models.py

class Group(models.Model):
    name = models.CharField(max_length=60)

class Country(models.Model):
    name = models.CharField(max_length=60)
    groups = models.ManyToManyField(Group, related_name='groups')

views.py

def countries(request):
    queryset = Country.objects.annotate(json=AsGeoJSON('mpoly'))
    data = serializers.serialize(
        'geojson',
        queryset,
        geometry_field='mpoly',
        fields=('name', 'groups')
    )
    return HttpResponse(data)

The output geojson does not include nested groups for each country. How to add them into the features / properties field?

1

There are 1 best solutions below

0
willeM_ Van Onsem On

You can do this by aggregating with ArrayAgg [Django-doc]:

from django.contrib.postgres.aggregates import ArrayAgg


def countries(request):
    queryset = Country.objects.annotate(
        json=AsGeoJSON('mpoly'), group_names=ArrayAgg('groups__name')
    )
    data = serializers.serialize(
        'geojson',
        queryset,
        geometry_field='mpoly',
        fields=('name', 'group_names'),
    )
    return HttpResponse(data)

But from the moment serialization becomes more complicated, you probably better use the Django REST framework [drf-doc], which provides more sophisticated and complicated serialization.