From 66a04f3025d5db4b4d18c12d81e7b1ccdc2250c3 Mon Sep 17 00:00:00 2001 From: kj1352 Date: Thu, 21 Jul 2022 17:25:17 +0530 Subject: [PATCH] Added related name and showing read only item details in invoice list --- invoice/models.py | 15 ++++++++++++++- invoice/serializers.py | 5 ++++- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/invoice/models.py b/invoice/models.py index ae94074..d3a68ab 100644 --- a/invoice/models.py +++ b/invoice/models.py @@ -1,5 +1,6 @@ from django.db import models from project.models import Project +from client.models import Client, Address, TaxType class Invoice(models.Model): @@ -19,6 +20,18 @@ class Invoice(models.Model): total += item.item_total return total + @property + def invoice_total_after_tax(self): + items = Item.objects.filter(invoice=self.pk) + project = Project.objects.get(client=self.project) + client = Client.objects.get(pk=project.client) + address = Address.objects.get(pk=client.address) + tax_type = TaxType.objects.get(pk=address.tax_type) + total = 0 + for item in items: + total += item.item_total + return total + def __str__(self): return self.invoice_id @@ -27,7 +40,7 @@ class Item(models.Model): name = models.TextField(blank=False, null=False) amount = models.DecimalField(max_digits=15, decimal_places=2) quantity = models.IntegerField() - invoice = models.ForeignKey(Invoice, on_delete=models.CASCADE) + invoice = models.ForeignKey(Invoice, on_delete=models.CASCADE, related_name='items') @property def item_total(self): diff --git a/invoice/serializers.py b/invoice/serializers.py index a68004b..880e1c4 100644 --- a/invoice/serializers.py +++ b/invoice/serializers.py @@ -9,6 +9,9 @@ class ItemSerializer(serializers.ModelSerializer): class InvoiceSerializer(serializers.ModelSerializer): + items = ItemSerializer(many=True, read_only=True) + class Meta: model = Invoice - fields = ['id', 'title', 'project', 'invoice_id', 'raised_date', 'due_date', 'paid_date', 'is_archived', 'invoice_total'] + fields = ['id', 'title', 'project', 'invoice_id', 'raised_date', 'due_date', 'paid_date', 'is_archived', + 'invoice_total', 'items']