Clever way to iterate over all query results with the same attribute


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
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.

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)

Need Your Help

Some questions with NetFSMountURLAsync?

objective-c osx cocoa

I am working on a OS X app which mount server volumes through NetFSMountURLAsync. And now I have many questions.

Django database inquiries. Finding duplicates in the database and stopping them from being submitted

python database django

I'm trying to go inside of my database and see if a certain submission has been submitted before and if it has stop it from being submitted again. Currently I have this bit of code testing each fie...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.