sajid
sajid

Reputation: 883

How to query self referencing queries in Django for multiple objects

Sorry for the bad title. I hope I can elaborate it better here. I have a model class as below

class Employee(models.Model):
    name = models.CharField(max_length=10)
    manager = models.ForeignKey('Employee', null=True, on_delete=models.DO_NOTHING)

I want to make a query to find all the employees managed by a list of managers.

Something like this

SELECT
r.name
FROM employee l
JOIN employee r
ON l.id = r.manager_id
WHERE l.name in ('manger_1', 'manager_2');

How can I achieve this with Django ORM?

Upvotes: 1

Views: 298

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476659

You can filter with an __in lookup [Django-doc]:

Employee.objects.filter(manager__name__in=['manager_1', 'manager_2'])

Upvotes: 1

Related Questions