巧妙地使用相同属性迭代所有查询结果

时间:2012-08-19 16:46:27

标签: python django

假设:

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

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

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分: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)