I’d like to know if anyone already succeeded in joining two models that relate only on their geometry fields, without raw SQL. My use case is to annotate a parent model containing a polygon field with the number of points (PointField of another model) contained in each parent model instance.
SELECT
polygonmodel.*,
COUNT(pointmodel.id)
FROM polygonmodel
LEFT JOIN polygonpoint ON (
ST_Within(polygonpoint.point, polygonmodel.polygon)
)
GROUP BY polygonmodel.id
Not possible today unless you rely on one of the linked third-party solution though so you have to get creative.
In your case I don’t see how you can avoid a RawSQL annotation or a Subquery subclass unfortunately as even if there are ways to do aggregation through annotations in subqueries you need to be able to group by a particular column for the workaround to work and in your case you want an aggregation without grouping by the child table.
Wow, thanks a lot @charettes for this awesomely documented answer. It’s so precious to know that something is not possible, otherwise you can spent hours trying without hope! Thanks also for the pointer to the Subquery subclass.
Thanks also @KenWhitesell for trying to help on this!