Search code examples
djangoormdjango-orm

Django Find parent by two children


class Company(models.Model):  
    title = models.CharField()  

class Office(models.Model):  
    сompany = models.ForeignKey(Company, on_delete=models.CASCADE)  
    title = models.CharField()  

class Human(models.Model):  
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    office = models.ManyToManyField(Office)

how to find current user's company without using Prefetch. Because it's expensive


Solution

  • You can try like this:

    >> user = request.user
    >> Company.objects.filter(office__human__user=user)
    

    Here I am reverse querying User from Company via Company --> Office --> Human --> User. More information can be found in the documentation.