1

认为:

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

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

4

2 回答 2

2

您需要按客户列出的项目列表,这听起来像是一个简单的循环。

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)
于 2012-08-19T17:05:15.400 回答
0

我可能会首先将每个客户的所有记录汇总到字典中:

from collections import defaultdict
items = ItemToBill.objects.filter(date_to_bill=BEFORE_TODAY).order_by(customer)
bills_by_customer = defaultdict(list)
for bill in items:
    bills_by_customer[bill.customer.pk].append(bill)

然后你可以遍历分组字典:

for customer_pk, bills in bills_by_customer.iteritems():
    createInvoice(customer_pk, bills)
于 2012-08-19T17:05:33.850 回答