Alexander
Alexander

Reputation: 1345

Is it possible to select the polygon with the maximum area with a query in GeoDjango or PostGIS?

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

Answers (2)

John Powell
John Powell

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

Mike T
Mike T

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

Related Questions