# Join two models on geometry predicate

**URL:** <https://forum.djangoproject.com/t/join-two-models-on-geometry-predicate/25319>\
**Category:** Using the ORM\
**Created:** [November 14, 2023, 11:29am UTC](https://forum.djangoproject.com/t/join-two-models-on-geometry-predicate/25319 "2023-11-14T11:29:56Z")\
**Posts on this page:** 7\
**Page:** 1

<div class="post-metadata">

**Author:** ![claudep](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/claudep/32/5377_2.png) [@claudep](https://forum.djangoproject.com/u/claudep)\
**Post date:** [November 14, 2023, 11:29am UTC](https://forum.djangoproject.com/t/join-two-models-on-geometry-predicate/25319/1 "2023-11-14T11:29:56Z")

</div>

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.

I found this StackOverflow post ([python - GeoDjango query: all point that are contained into a multi polygon - Stack Overflow](https://stackoverflow.com/questions/37166891/geodjango-query-all-point-that-are-contained-into-a-multi-polygon/47263632)) which is close to what I’m trying to achieve, but I’m unfortunately getting errors. I can develop my trials/errors, but I’d like first to know if someone found a solution for a similar use case.

Any success story here?

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [November 14, 2023, 1:29pm UTC](https://forum.djangoproject.com/t/join-two-models-on-geometry-predicate/25319/2 "2023-11-14T13:29:28Z")

</div>

If that SO answer is on-point and still relevant, it may be helpful if you posted what you tried and the errors you received when trying it.

---

<div class="post-metadata">

**Author:** ![claudep](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/claudep/32/5377_2.png) [@claudep](https://forum.djangoproject.com/u/claudep)\
**Post date:** [November 14, 2023, 2:29pm UTC](https://forum.djangoproject.com/t/join-two-models-on-geometry-predicate/25319/3 "2023-11-14T14:29:39Z")

</div>

First try (like suggested on SO post):

```auto
PolyModel.objects.annotate(
    contained_points=Subquery(
        PointModel.objects.filter(
            point__within=OuterRef('polygon')
        )
    )
)

```

Result: `FieldError: Cannot resolve expression type, unknown output_field`

Second try:

```auto
PolyModel.objects.annotate(
    contained_points=Subquery(
        PointModel.objects.filter(
            point__within=OuterRef('polygon')
        ), output_field=IntegerField(),
    )
)

```

Result: `ProgrammingError: ERROR: Subquery must return only one column`

Another try:

```auto
PolyModel.objects.annotate(
    contained_points=Subquery(
        PointModel.objects.filter(
            point__within=OuterRef('polygon')
        ).aggregate(num=Count('id'))['num'],
        output_field=IntegerField(),
    )
)

```

Result: `ValueError: This queryset contains a reference to an outer query and may only be used in a subquery.`

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [November 14, 2023, 3:24pm UTC](https://forum.djangoproject.com/t/join-two-models-on-geometry-predicate/25319/4 "2023-11-14T15:24:28Z")

</div>

I think this is closest:

> [@claudep](#):
>
> ```auto
> PolyModel.objects.annotate(
> contained_points=Subquery(
> PointModel.objects.filter(
> point__within=OuterRef('polygon')
> ), output_field=IntegerField(),
> )
> )
> 
> ```

(I’m winging this)

My first attempt would be to try:

```auto
PolyModel.objects.annotate(
    contained_points=Subquery(
        PointModel.objects.filter(
            point__within=OuterRef('polygon')
        )
    ).count()
)

```

or possibly:

```auto
PolyModel.objects.annotate(
    contained_points=Subquery(
        PointModel.objects.filter(
            point__within=OuterRef('polygon')
        )
    ).count(), output_field=IntegerField()
)

```

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [November 14, 2023, 3:38pm UTC](https://forum.djangoproject.com/t/join-two-models-on-geometry-predicate/25319/5 "2023-11-14T15:38:27Z")

</div>

Yea, … that’s not going to work.

I’m going to play with some ideas to see what I can get to work.

---

<div class="post-metadata">

**Author:** ![charettes](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/charettes/32/27_2.png) [@charettes](https://forum.djangoproject.com/u/charettes)\
**Post date:** [November 14, 2023, 11:38pm UTC](https://forum.djangoproject.com/t/join-two-models-on-geometry-predicate/25319/6 "2023-11-14T23:38:02Z")

</div>

@claudep here’s how I would approach it

Ideally the ORM would [allow you define relationships between models that don’t involve foreign keys](http://charettes.name/djangoconus2022/slides.html#39) so you could do

```python
class PointField(models.Model):
    point = models.PointField()

class PolygonModel(models.Model):
    polygon = models.PolygonField()
    contained_points = Relation(PointField, Q(
        contained_points __point__ within=F("polygon"),
    ))

```

And then simply do

```python
PolygonModel.objects.annotate(Count("contained_points))

```

Which would result in the following SQL

```sql
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](https://code.djangoproject.com/ticket/28296#comment:17) and in your case you want an aggregation without grouping by the child table.

Proper support for [passing subqueries to aggregation function](https://code.djangoproject.com/ticket/28296) would address your issue as you could _simply_ do

```python
PolygonModel.objects.annotate(Count(
    PointField.objects.filter(point__within=OuterRef("polygon"))
))

```

I’m afraid until this lands you’ll have to create your own `Subquery` subclass that [wraps a the SQL into a different template](https://code.djangoproject.com/ticket/28296#comment:4).

---

<div class="post-metadata">

**Author:** ![claudep](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/claudep/32/5377_2.png) [@claudep](https://forum.djangoproject.com/u/claudep)\
**Post date:** [November 15, 2023, 7:48am UTC](https://forum.djangoproject.com/t/join-two-models-on-geometry-predicate/25319/7 "2023-11-15T07:48:32Z")

</div>

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!
