I have tried different ways of querying my data, but still results in a large amount of pings to the DB.
I have tried using select_related
.
Here are my models:
class Order(models.Model):
num = models.CharField(max_length=50, unique=True)
class OrderInfo(models.Model):
info = models.CharField(max_length=100, unique=True)
datetime = models.DateTimeField(auto_now_add=True, blank=True)
order_fk = models.ForeignKey(Order)
What I am trying to achieve:
OrderInfo
has a bunch of information pertaining to the Order
.
What I want is to be able to get the most recent OrderInfo
from the DB, but I want it unique to Order
. The unique part is where I am struggling to minimize my query amount.
ois = OrderInfo.objects.order_by('-datetime').select_related('order_fk')
When I try to filter it is doing a query on each Order to check for uniqueness the queries ramp up.
For instances:
_ = [oi.order_fk for oi in ois] # queries reach to 20k, takes too long.
Also, then I just need to limit how many responses I get, but I need to know how many unique Orders
there are first in order to limit it.
Anyone, know a proper approach to minimize these queries or possibly I may need to restructure my models.
Notes:
- Django 1.7
- Python 2.7
- SQLite