gpt4 book ai didi

python - 迭代具有相同属性的所有查询结果的巧妙方法

转载 作者:行者123 更新时间:2023-12-01 05:56:56 24 4
gpt4 key购买 nike

假设:

class ItemToBill(models.Model):
date_to_bill = fields.DateField()
description = fields.charfield()
customerToBill = fields.ForeignKey(Customer)

我想找到今天之前应计费的所有项目,然后按客户对它们进行分组,以便我可以为每个需要的客户创建一张发票。

for unique_customer in all_unique_customers_with_items_to_bill:
createInvoice(unique_customer, their_items_to_bill)

我可能可以做一些事情,查询商品(由客户订购),然后确定何时输入新客户的商品集。这看起来像:

items = ItemToBill.objects.filter(date_to_bill=BEFORE_TODAY).order_by(customer)
prevCustomer = items[0].customer
customer_items = []
for item in items:
if prevCustomer != item.customer:
createInvoice(prevCustomer, customer_items)
customer_items = []
prevCustomer = item.customer
customer_items.append(item)
createInvioce(prevCustomer, customer_items) #Handle the last customer

但是必须有一个更聪明的解决方案。有建议吗?

最佳答案

您需要客户的商品列表,这听起来像是一个简单的循环。

items_by_customer = {}

for item in ItemToBill.objects.filter(...date_query...):
items_by_customer.setdefault(item.customerToBill, []).append(item)

for customer, items in items_by_customer.items():
print customer, items # items grouped by customer.
# generate_invoice(customer, items)

关于python - 迭代具有相同属性的所有查询结果的巧妙方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12028208/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com