Search code examples
djangogeodjango

Pass a list to geodjango multipolygon lookup


I have a list of points like following:

points_list = [<Point object at 0x7f92b96103c8>, <Point object at 0x7f92b96105e8>]

Now I want to use this list to filter on a MultipolygonField. I can't pass this whole list to the multipolygon lookup because I get an error, Tuple too long for lookup covers.

Now what I have done is simply loop through the list and save the filtered multipolygon objects in a new list like:

Say geom below is a multipolygon field

multipolygon_list = []
for point in points_list:
    dam_obj = DAM.objects.filter(geom__contains=point).values_list('id', flat=True)
    multipolygon_list.append(dam_object)

Now what I want is to remove the loop above and all this is a single query. Is there a way to remove it? Like can't I do something like below?

DAM.objects.filter(geom__contains=points_list)...

Solution

  • Answering my own question as I find the solution. So I wanted to remove the loop.

    I made a union of the Points list and created a single Multipoint and then passed that multipoint to the lookup.

    from django.contrib.gis.db.models import Union
    single_multipoint = Union(points_list)
    
    # pass the single multipoint to the lookup.
    DAM.objects.filter(geom__contains=single_multipoint)