1

I'm trying to annotate a queryset of Entity objects with the distance between two related polygons; each entity has its own set of related polygons, stored in the shape attribute of foreign-key-related EntityFeature objects. EntityFeatures are named, and I need to find the distance between two named features for each entity:

Entity.objects.all().annotate(
    distance = ExpressionWrapper(
        Subquery(
            EntityFeature.objects.get(
                entity__id = OuterRef('id'),
                name = 'feature_a'
            ).shape.centroid.distance(
                Subquery(
                    EntityFeature.objects.get(
                        entity__id = OuterRef(OuterRef('id')),
                        name = 'feature_b'
                    ).shape.centroid
                )
            )
        ), output_field = DecimalField()
    )
)

As soon as it reaches the first OuterRef, I get ValueError: This queryset contains a reference to an outer query and may only be used in a subquery. I've tried removing the first subquery and using F('id'), but then I think id refers to the EntityFeature's id instead and it throws DoesNotExist: EntityFeature matching query does not exist.

Am I going about this the wrong way? What's the best method to find the distance between two related objects for each thing in a queryset?

[python 2.7.15 / django 1.11]

bribroder
  • 86
  • 6

0 Answers0