I have two models in my application:

class Organization(models.Model):
    consortium = models.ForeignKey('Consortium')
    org_map = models.MultiPolygonField()

class Consortium(models.Model):
    cons_map = models.MultiPolygonField()

I'm trying to write some code that will union all the org_maps for organizations in a consortium, but am having trouble.

The documentation leads me to believe that this is possible, I'm just a little off.

What I have so far is this:

from django.contrib.gis.db.models import functions as geodjango_functions

for consortium in Consortium.objects.all():
    for organization in Organization.objects.filter(consortium=consortium):
        if not consortium.cons_map:
            cons_map = organization.org_map
            union = geodjang_functions.Union(consortium.cons_map, organization.org_map)
            consortium.cons_map = union.geo_field

Unfortunately, this does not seem to work. Running the code doesn't produce any errors, but the resulting cons_map is always just the org_map for the last organization in that consortium. Any pointers about what exactly I'm doing wrong would be wonderful.


Union is an aggregate function. In this case you would use it like this:

from django.contrib.gis.db.models.aggregates import Union

for consortium in Consortium.objects.all():
    geom_union = Organization.objects.filter(consortium=consortium).aggregate(union=Union('org_map'))
    consortium.cons_map = geom_union["union"]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.