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?
You can do this by aggregating with
ArrayAgg[Django-doc]: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.