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
.queryto the end of your query (ois) and provide the result? You can post the results on a site like poorsql.com to avoid character limit here and provide formatting. In general, this will post out the query as Django is creating it and we can leverage that to try and see what exactly is causing it to query so much. Also, how many orders are there in your database? How many info objects are there in your database?goo.gl/czqYru. When I do the for loop it is doing that query every time. There are about 4kOrdersand about 35kOrderInfos. PS: Won't me let paste short link and original link is extremely long.OrderInfoobjects, the most recent, regardless ofOrder, but only once perOrder, is that correct? I'm not sure I'll be able to help with reducing this with the way the models are set up.