我在Django中有这个模型:
型号.py
class Transaction(models.Model):
ref_code = models.CharField()
buyer = models.ForeignKey(User)
product = models.ForeignKey(Product)
quantity = models.IntegerField()
ref_code
不是唯一的。
数据是这样的:
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
如何在基于ref_code
的模板中查看buyer
、product
和quantitiy
?所以,它看起来是这样的:
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
有两种方法,第一种是简单的方法,按ref id排序并继续处理数据,除非ref id发生变化,第二种是稍微提前一点,需要您做一些类似。。。
qs = Transaction.objects.values("ref_code").annotate(
buyers=ArrayAgg("buyer"),
products = ArrayAgg("product"),
quantities=ArrayAgg("quantity"))
发布这篇文章只需运行for循环并格式化您的数据。