I am new to django. I am working on a test project. Where I have a Model CollectFee
with structure given below:
class CollectFee(models.Model):
boarder = models.ForeignKey(Boarder, on_delete=models.CASCADE)
feetype = models.ForeignKey(FeeType, on_delete=models.CASCADE)
amountdue = models.PositiveIntegerField("amount Due")
amountpaid = models.PositiveIntegerField("amount Paid")
balance = models.PositiveIntegerField("Balance")
class Meta:
verbose_name_plural = "Collect Fee"
def __str__(self):
return self.boarder.name
I want to apply a query set in the views which will display all the records where feetype_id
is not 2, when this record is excluded then also exclude those records which have the same boarder_id
as of already excluded record.
For example, Exclude the second row as it has feetype_id = 2
then also exclude the third row because it has the same boarder_id
as of second row.
As I am new, I was able to just implement the filter below:
def feedue(request):
last_fee_type = FeeType.objects.last()
boarders = CollectFee.objects.exclude(feetype_id=last_fee_type)
context = {'boarders':boarders}
return render(request, 'fee-due.html', context)
CodePudding user response:
You can exclude the many-to-one relationship with the through accessor like this:
CollectFee.objects.exclude(boarder__collectfee__feetype=last_fee_type)
This expression essentially gets the Boarder from a particular CollectFee object, then all CollectFees associated with that Boarder and their FeeTypes, allowing you to exclude accordingly.
CodePudding user response:
May be this helps
def feedue(request):
excluded_objs = CollectFee.objects.filter(feetype_id=2)
border_ids = [ids for obj.border_id in excluded_objs]
duefee = CollectFee.objects.exclude(boarder_id__in=border_ids)
context = {'duefee': duefee}
return render(request, 'fee-due.html', context)