How to optimize Django ORM to use outer join instead of subquery when self-referencing fields?

org_id = attrs.get('organization_id')
person_name = attrs.get('name', getattr(self.instance, 'name', None))

existing_entries = LeadModel.objects.filter(
    role='manager',
    organization_id=org_id,
    is_converted=True
)
if self.instance:
    # Exclude current instance in case of update
    existing_entries = existing_entries.exclude(id=self.instance.id)

if existing_entries.exists():
    raise serializers.ValidationError({
        "message": "A manager already exists for this organization. You cannot create a new one."
    })

try:
    org_data = LeadModel.objects.get(unique_id=org_id)
    if not org_data.owner_name or org_data.owner_name.strip().lower() != person_name.strip().lower():
        org_data.owner_name = person_name
        org_data.save(update_fields=['owner_name'])
except ObjectDoesNotExist:
    pass

return attrs

Hello there,

You are unlikely to get an answer here without providing the queries that are causing you trouble and what you’d like them to look like.

From what I can see there should be not use of subqueries here as exclude will only use them when filtering against multi-valued relationships

All I can see in terms of queries here are

SELECT 1
FROM leadmodel
WHERE
    role = 'manager'
    AND organization_id = ?
    AND is_converted
    AND NOT (id = ?)
LIMIT 1
---
SELECT * FROM leadmodel WHERE id = ?
---
UPDATE leadmodel SET owner_name = ? WHERE id = ?

by the way it looks it looks like you re-implemented exactly what a conditional unique constraint on LeadManager would have achieved by itself

class LeadManager(models.Model):
    ...
    class Meta:
        constraints = [
            UniqueConstraint(
                fields=["organization_id"],
                condition=Q(role="manager", is_converted=True),
            )
        ]