Assume:
class ItemToBill(models.Model):
date_to_bill = fields.DateField()
description = fields.charfield()
customerToBill = fields.ForeignKey(Customer)
I want to find all items that should be billed before today, and then group them by customer so I can create a single invoice for each customer that needs it.
for unique_customer in all_unique_customers_with_items_to_bill:
createInvoice(unique_customer, their_items_to_bill)
I could probably do something where I query the items (ordering by the customers) and then identifying when I’ve entered a new customer’s set of items. This would look like:
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
but there’s got to be a more clever solution. Suggestions?
You need a list of items by customer, which sounds like a simple loop.