简体   繁体   中英

Why my contained Query doesnot work in spatial coordinates in GeoDjango?

I am trying to use a Polygon which is defined as follows:

from django.contrib.gis.geos import Polygon

parcel = Parcel.objects.filter(objectid="22520").values()
geojson = parcel[0]['geom'].geojson
format_l = ast.literal_eval(geojson)
coordinates_data = format_l['coordinates'][0][0]

poly = Polygon(coordinates_data, srid=3492)
poly_parcel = poly.transform(4326, clone=True)
polygon = poly_parcel.coords
print(polygon)

polygon then contains the following as shown:

 (((-121.49440799279022, 38.55725848782723),
  (-121.49438844924772, 38.557303481514126),
  (-121.4943760310021, 38.5573320694682),
  (-121.49436263531841, 38.557362909896675),
  (-121.49402385986245, 38.557269114460084),
  (-121.49406987333441, 38.55716268909225),
  (-121.49440799279022, 38.55725848782723)),)

I want to locate the Primary data within the Parcel Data, so I tried this:

 Primary.objects.filter(geom__contains=polygon).values()
 #and also tried with contained lookup
 Primary.objects.filter(geom__contained=polygon).values()

When I try this query it throws this error:

"ValueError: Cannot use object with type tuple for a spatial lookup parameter."

Even trying with a List, I am getting the same error...

Let's analyze the error and see from there ( Emphasis mine ):

"ValueError: Cannot use object with type tuple for a spatial lookup parameter ."

So you are trying to use a tuple object as an argument in a spatial lookup. If you see how you define your polygon, it is clear that this is the culprit:

(((-121.49440799279022, 38.55725848782723),
  (-121.49438844924772, 38.557303481514126),
  (-121.4943760310021, 38.5573320694682),
  (-121.49436263531841, 38.557362909896675),
  (-121.49402385986245, 38.557269114460084),
  (-121.49406987333441, 38.55716268909225),
  (-121.49440799279022, 38.55725848782723)),) # Defenitely a tuple!!!

And you are getting the error when you try to use it on a spatial query:

Primary.objects.filter(geom__contains=polygon).values()

I would suggest sticking with GeoDjango's geometries (which you are already using) as shown in the documentation, and more specifically with the GEOS Polygon :

  • Define your polygon as a GEOS Polygon:

     from django.contrib.gis.geos import Polygon parcel = Parcel.objects.filter(objectid="22520").values() geojson = parcel[0]['geom'].geojson format_l = ast.literal_eval(geojson) coordinates_data = format_l['coordinates'][0][0] geos_poly = Polygon(coordinates_data, srid=3492) polygon = geos_poly.transform(4326, clone=True) 
  • Use this polygon in the spatial query:

     Primary.objects.filter(geom__contains=polygon).values() 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM