Reputation: 1345
I have lots of urban area multipolygons and I need to select the one with the largest area. At the moment I iterate through each object and calculate the area for each but this is inefficient. What is the best way to do this?
Upvotes: 2
Views: 2103
Reputation: 12581
I am not sure if you can call ST_Area directly in GeoDjango, in conjunction with an aggregate query, but you could use a raw SQL query. For example, using the correct Postgres query, as posted by @MikeT,
top_area = ModelName.objects.raw('SELECT * FROM sometable ORDER BY ST_Area(geom) DESC LIMIT 1')[0]
Upvotes: 3
Reputation: 43702
With SQL, this query is:
SELECT *, ST_Area(geom) FROM mytable ORDER BY ST_Area(geom) DESC LIMIT 1;
This calculates area for each geometry for the whole table.
If you use ST_Area(geom)
frequently, you can make an index on the expression:
CREATE INDEX mytable_geom_area_idx ON mytable (ST_Area(geom))
Upvotes: 1