Search code examples
pythondjangopython-3.xdjango-2.1

Django - annotate latest child's column value to query


I have a Trade, which is the parent of TradeLeg. I am now querying the trade and I need to annotate the "date" of the latest TradeLeg added to this query.

Here's my models:

class Trade(models.Model):
    name = models.CharField(
        default='',
        max_length=50,
        blank=True,
    )
    date = models.DateField(
        default='',
        blank=True,
        null=True,
    )


class TradeLeg(models.Model):
    trade = models.ForeignKey(
        Trade,
        on_delete=models.CASCADE
    )
    date = models.DateField(
        default='',
        blank=True,
        null=True,
    )

Here's my erroneous query:

trades = Trade.objects.all().annotate(latest_leg_date='tradeleg__date__first')

Solution

  • Try to use Max() function

    from django.db.models import Max
    
    trades = Trade.objects.all().annotate(latest_leg_date=Max('tradeleg__date'))