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
x
30
30
1
from django.db import models
2
3
# My classes
4
class Customer(models.Model):
5
name = models.CharField("Name", max_length=50, unique=True)
6
7
class Item(models.Model):
8
name = models.CharField("Name", max_length=50, unique=True)
9
10
class Purchase(models.Model):
11
customer = models.ForeignKey("Customer", on_delete=models.CASCADE)
12
item = models.ForeignKey("Customer", on_delete=models.CASCADE)
13
14
# My data
15
purchase_table =[
16
{'customer': 'Joe', 'item': 'Toaster'},
17
{'customer': 'Joe', 'item': 'Slippers'},
18
{'customer': 'Jane', 'item': 'Microwave'}
19
]
20
21
# Populating DB
22
for purchase in purchase_table:
23
24
# Get item and customer (this is where the inefficient use of 'get' takes place)
25
item = Item.objects.get(name=purchase['item'])
26
customer = Customer.objects.get(name=purchase['customer'])
27
28
# Create new purchase
29
Purchase(customer, item).save()
30
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
1
6
1
items = {item.name: item for item in Item.objects.all()}
2
customers = {customer.name: customer for customer in Customer.objects.all()}
3
4
purchases = [Purchase(customers[c], items[i]) for c, i in zip(items, customers)]
5
Purchase.objects.bulk_create(purchases)
6