Join two tables through third one with two foreign keys

I have three tables:

class Bank(models.Model):
    ...

class Deposit(models.Model):
    ...

class DepositProposal(models.Model):
    percent = models.FloatField()
    deposit = models.ForeignKey(Deposit)
    bank = models.ForeignKey(Bank)

Bank can participate in deposit auction applying DepositProposal instance. How can I filter Deposit rows which bank hasn't participated yet? Found that I should use two LEFT JOIN but I didn't come across it. Using PosgtreSQL.

If you want to know the deposits in which a bank does not participate:

1- Add a related_name to deposit and bank:

class DepositProposal(models.Model):
    percent = models.FloatField()
    deposit = models.ForeignKey(Deposit, related_name = "proposals")
    bank = models.ForeignKey(Bank, related_name = "proposals")

2- Get the bank that you want to check:

bank = Bank.objects.first() #For example, the first bank

3- Get the queryset:

deposits = Deposit.objects.exclude(proposals__bank = bank)

EDIT:

If you want to know the banks that not participate on a specific deposit:

deposit = Deposit.objects.first() #For example, the first deposit
banks = Bank.objects.exclude(proposals__deposit = deposit)
Back to Top