假设:
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)