2

I have 2 models

class Store(models.Model):
    name = models.Charfield()

class Book(models.Model):
    name = models.Charfield()
    timestamp = models.Datetimefield()
    store = models.ForeignKey(store)

What i currently do to get the latest book for each store is this:

stores = Store.objects.filter(name__contains = "stackoverflow")
latest_books = []
for store in stores:
    latest_books.append(Book.objects.filter(store_id = store.id).latest("timestamp"))

However this can result in an insane amount of queries if there are too many stores

Is it possible to do this in one single query and how?

Im using django 1.5 and mysql, so the .distinct("timestamp") is not supported by mysql :)

Agey
  • 891
  • 8
  • 17
  • i dont really have any knowledge about sql but i think it will be faster the way you do it right now then with a single query (if that is even possible) – yamm Mar 23 '15 at 14:08
  • 1
    What you're looking might be answered in this question: http://stackoverflow.com/questions/13403609/how-to-group-by-and-aggregate-with-django. Maybe have a look over there? – Exelian Mar 23 '15 at 16:05
  • 1
    If you need this information frequently, maybe it would be good idea to add the field ```latest_book = models.ForeignKey(to=Book, null=True, blank=True)``` to your ```Store``` model. – Ihor Pomaranskyy Mar 23 '15 at 16:24

0 Answers0