class Profile(models.Model):
user = models.OneToOneField(User, verbose_name=_('user'), related_name='profile', blank=True, null=True)
phone = models.CharField(_("phone"), max_length=30, blank=True, null=True)
class Unit(models.Model):
owner = models.ForeignKey(Profile, verbose_name=_("owner"), related_name="owned_units", blank=True, null=True)
tenant = models.ForeignKey(Profile, verbose_name=_("tenant"), related_name="tenanted_units", blank=True, null=True)
name = models.CharField(_("unit name"), max_length=255)
Profile.objects.annotate(owned_count=Count('owned_units'), tenanted_count=Count('tenanted_units'))\
.filter(Q(owned_count__gt=0) | Q(tenanted_count__gt=0))
SELECT "profiles_profile"."id", "profiles_profile"."user_id", "profiles_profile"."phone",
COUNT("units_unit"."id") AS "owned_count",
COUNT(T4."id") AS "tenanted_count" FROM "profiles_profile"
INNER JOIN "auth_user" ON ("profiles_profile"."user_id" = "auth_user"."id")
LEFT OUTER JOIN "units_unit" ON ("profiles_profile"."id" = "units_unit"."owner_id")
LEFT OUTER JOIN "units_unit" T4 ON ("profiles_profile"."id" = T4."tenant_id")
WHERE ("auth_user"."is_active" = True )
GROUP BY "profiles_profile"."id", "profiles_profile"."user_id", "profiles_profile"."phone"
HAVING (COUNT("units_unit"."id") > 0 AND COUNT(T4."id") > 0 )
Добавлю, что exclude(owned_count=0, tenanted_count=0), которое бы мне тоже подошло, работает так же неверно и генерирует сдедующий HAVING:
HAVING (NOT (COUNT("units_unit"."id") = 0 ) AND NOT (COUNT(T4."id") = 0 ))