I have two models like this:
class Store(models.Model):
name = models.CharField(max_length=255)
class Order(models.Model):
store = models.ForeignKey(Store)
date = models.DateTimeField(auto_now_add=True)
success = models.BooleanField()
I would like to filter all the records from the Store model whose latest order was successful i.e. success == True.
Although it looks very simple, I’m having issues figuring how I would accomplish this using the ORM query system.
Any help? Thanks.
My approach is this: do 2 lists, first one with (id_store, last_success_date) tuples and second one with (id_store, last_date) tuples:
Then take store ids for stores that last data and last success date are equals, and you have the query:
It seems an elegant solution, only four lines of code for a complex query (but with a simple requeriment). Disclaimer, it is not tested.