Home > front end >  Django Nested Group By Data in template
Django Nested Group By Data in template

Time:03-16

here I explain my model, data, table structure, and expected result.

My models are given below:

class Buyer(models.Model):
   name = models.CharField(max_length=100)
   code = models.CharField(max_length=20

class Merchand(models.Model):
   name = models.CharField(max_length=100)
   code = models.CharField(max_length=20

class Order(models.Model):
   code = models.CharField(max_length=20)
   buyer = models.ForeignKey(CustomUser, on_delete=SET_NULL, related_name='br_order')
   merchand = models.ForeignKey(CustomUser, on_delete=SET_NULL, related_name='mr_order')
   value = models.FloatField(null=True, blank=True)
   qty = models.FloatField(null=True, blank=True)

this is my model structure and my order model data is like this:

{'code': 'C-001', 'buyer': 1, 'merchand': '1', 'qty': 100, 'value': '100'}
{'code': 'C-002', 'buyer': 1, 'merchand': '1', 'qty': 100, 'value': '300'}
{'code': 'C-003', 'buyer': 2, 'merchand': '2', 'qty': 100, 'value': '400'}
{'code': 'C-004', 'buyer': 3, 'merchand': '2', 'qty': 700, 'value': '400'}
{'code': 'C-005', 'buyer': 2, 'merchand': '2', 'qty': 900, 'value': '4500'}
{'code': 'C-006', 'buyer': 2, 'merchand': '3', 'qty': 200, 'value': '2000'}
{'code': 'C-007', 'buyer': 3, 'merchand': '2', 'qty': 700, 'value': '400'}
{'code': 'C-008', 'buyer': 2, 'merchand': '2', 'qty': 900, 'value': '4500'}
{'code': 'C-009', 'buyer': 2, 'merchand': '3', 'qty': 200, 'value': '2000'}

I want to generate a table like this:

= Buyer: 1, qty: 200, value: 400
   - code: C-001, qty: 100, value: 100
   - code: C-002, qty: 100, value: 300 

= Buyer: 2, qty: 200, value: 13400
   - code: C-003, qty: 100, value: 400
   - code: C-005, qty: 900, value: 4500
   - code: C-006, qty: 200, value: 2000
   - code: C-008, qty: 900, value: 4500
   - code: C-009, qty: 200, value: 2000

= Buyer: 3, qty: 1400, value: 800
   - code: C-004, qty: 700, value: 400 
   - code: C-007, qty: 700, value: 400 

how I show this type of data?

CodePudding user response:

For each title use this queryset:

from django.db.models import Sum
result = (Order.objects
    .values('buyer')
    .annotate(qty=Sum('qty'))
    .annotate(value=Sum('value'))
)

For each buyer select buyer:

for x in result:
    print(x)
    buyer_order = Order.objects.filter(buyer = x['buyer'])
    for b in buyer_order:
        print(f'code = {b.code}, merchand = {b.merchand}, value = {b.value}, qty = {b.qty}')


  • Related