Advance django filters

I am working on a management system. Where I have models:

class FeeType(models.Model):
    name = models.CharField("fee Type", max_length=200)
    duedate = models.DateField("due date")

    class Meta:
        verbose_name_plural = "Fee Type"

    def __str__(self):
        return self.name

class CollectFee(models.Model):
    boarder = models.ForeignKey(Boarder, on_delete=models.CASCADE)
    feetype = models.ForeignKey(FeeType, on_delete=models.CASCADE)
    amountpaid = models.PositiveIntegerField("amount Paid")

    class Meta:
        verbose_name_plural = "Collect Fee"

    def __str__(self):
        return self.boarder.name

Now in a template I want to show the list of all the boarders/students, who have not been assigned the last fee. e.g if "July Fee" is the last object in the FeeType model then show all those boarders who have not been assigned the JulyFee.

I have tried a view for this:

def feedue(request):
    last_fee_type = FeeType.objects.last()

    boarders = CollectFee.objects.exclude(boarder__collectfee__feetype=last_fee_type)

    context = {'boarders':boarders}
    return render(request, 'fee-due.html', context)

It does not show the boarders who have been assigned the last feetype, that's correct. But if the boarder is not assigned the last feetype then it shows the boarder name as many times as he have been assigned the previous feetypes. Hope you understand. Help please.

You should be querying Boarder if you want a list of boarders. You can filter across the reverse Foreign Key relation (by default collectfee_set__whatever)

If you are using Postgres, you might add .distinct('boarder'). I don't know what a plain .distinct() will do with a different DB

Back to Top