Django distinct queryset

Viewed 31

I have this model in Django:

model.py

class Transaction(models.Model):
    ref_code = models.CharField()
    buyer = models.ForeignKey(User)
    product = models.ForeignKey(Product)
    quantity = models.IntegerField()

ref_code is not unique.

The Data is something like this:

id: 1, buyer: John, product : Book, quantity: 1, ref_code = 111111
id: 2, buyer: Thomas, product : Pencil, quantity: 3, ref_code = 111111
id: 3, buyer: Mary, product : Book, quantity: 2, ref_code = 222222
id: 4, buyer: Bryan, product : Origami, quantity: 2, ref_code = 222222
id: 5, buyer: Anna, product : Eraser, quantity: 5, ref_code = 111111
id: 6, buyer: Lily, product : Notebook, quantity: 1, ref_code = 222222

How can I view buyer, product, and quantitiy in a template based on ref_code? So, it will look like this:

REFERAL CODE: 111111
Buyer: John, Product : Book, Quantity: 1
Buyer: Thomas, Product : Pencil, Quantity: 3
Buyer: Anna, Product : Eraser, Quantity: 5

REFERAL CODE: 222222
Buyer: Mary, Product : Book, Quantity: 2
Buyer: Lily, Product : Notebook, Quantity: 1
Buyer: Bryan, Product : Origami, Quantity: 2
1 Answers

There are two ways to do, first is a simple one, order by ref id and keep processing the data unless the ref id changes, second is a bit advance, would require you to do something like...

    qs = Transaction.objects.values("ref_code").annotate(
           buyers=ArrayAgg("buyer"), 
           products = ArrayAgg("product"), 
           quantities=ArrayAgg("quantity"))

Post this just run a for loop and format your data.

Related