2

I'm using python 3.7, and django 2.1.

I'm trying to filter parent object by the "latest" kid object properties

I'm able to do so using 2 queries (see - Django Query That Get Most Recent Objects From Different Categories)

Class Bakery(models.Model):
     town = models.CharField()

Class Cake(models.Model):
    bakery = models.ForeignKey(Bakery, related_name="cakes")
    baked_at = models.DateTimeField()
    is_chocolate = models.BooleanField()

What I would like to do is something like:

bakeries_whose_latest_cake_was_chocolate = Bakery.objects \
    .annotate(latest_cake=F('cakes__baked_at=Max(cakes__baked_at')) \
    .filter(is_chocolate=True)
  • Try doing something like the following `Bakery.objects.filter(cakes__ is_chocolate=True).latest('cakes__baked_at')`. Note that `latest()` will only return a single object. – Marcell Erasmus Jan 22 '19 at 12:30
  • To my understanding, it won't solve the problem. It will return bakeries where there was at least one chocolate cake, not one where the LAST cake was chocolate. And the 'latest' bit will do nothing... – ori silberberg Jan 22 '19 at 14:32

0 Answers0