Skip to content
Advertisement

Reducing number of repeated queries in Django when creating new objects in a loop

I’m populating a database using Django from an Excel sheet. In the example below, the purchases list simulates the format of that sheet.

My problem is that I’m repeatedly using Customer.objects.get to retrieve the same Customer object when creating new Purchase entries. This results in repeated database queries for the same information.

I’ve tried using customers = Customer.objects.all() to read in the whole Customer table into memory, but that doesn’t seem to have worked since customers.get() still creates a new database query each time.

JavaScript

Advertisement

Answer

If you’re dealing with small enough data to read into memory, then why not use .all() like you mentioned? That should do the trick.

Something like:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement