items = Items.objects.filter(active=True)
price_list = []
for item in items:
price = Price.objects.filter(item_id = item.id).last()
price_list.append(price)
Price model can have multiple entry for single item, I have to pick last element. How can we optimize above query to avoid use of query in loop.
2
Answers
Try this:
If you’re using a Foreign Key to connect the Price and Item models, you can probably use this:
Another approach would be to get the item ids first and then filter based on those (as Hemal has mentioned previously, however I believe that the query in Hemal’s answer has a problem as it only provides the item ids whether the question needs the whole Price objects):
Also, in the question, you are picking the last price, without ordering it on anything. I believe that you should order it on the specific field you want to ignore any non-determinism.