1

In my manager, I've overriden get_queryset to annotate sqft_annotated value.

class RealestateManager(models.Manager):
    def get_queryset(self):
        return super().get_queryset().annotate(
            sqft_annotated=Coalesce('sqft_a', 'sqft_b', 'sqft_c')

I use this value frequently but now, in this query, it raises error (probably because it isn't annotated):

_a = Q(realestates__home_type__in=[constants.HOME_TYPES.HOME_TYPE__SINGLE_FAMILY, constants.HOME_TYPES.HOME_TYPE__FARM],
          realestates__sqft_annotated__gte=1100, ...)
_b = Q(<QUERY>)
_c = Q(<QUERY>)

leads_query = Q(Q(_a | _b) | ~_c)


Category.objects.annotate(lead_count=Count('realestates', filter=leads_query)).annotate(
            lead_perc=Case(When(lead_count=0, then=0), default=(Count(
                'realestates', filter=leads_query) / float(total)) * 100))

ERROR

Related Field got invalid lookup: sqft_annotated

Can I somehow use the sqft_annotated in such query?

PS: Tried to set base_manager_name in class Meta - didn't help.

Milano
  • 18,048
  • 37
  • 153
  • 353
  • The default manager (in your case `RealestateManager`) is not used for relations. For relations Django use base manager, which is typically `django.db.models.Manager`. See https://docs.djangoproject.com/en/3.1/topics/db/managers/#s-using-managers-for-related-object-access – quick Apr 01 '21 at 20:20
  • Same issue here. Would be really great to have an option to allow for querying related objects while making use of the annotations on that related object added through the manager. @Milano have you found any solution? – tbrlpld Apr 27 '21 at 00:42

0 Answers0