Christopher
Christopher

Reputation: 590

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')

Upvotes: 1

Views: 1327

Answers (2)

Usama Nadeem
Usama Nadeem

Reputation: 128

That's the simplest and professional way to get latest trades

latestTrades = Trade.objects.filter().order_by('-tradeleg__date')

However, if you use Max or Min function it will gives the same query.So that it can be cause an error

Upvotes: 1

JPG
JPG

Reputation: 88659

Try to use Max() function

from django.db.models import Max

trades = Trade.objects.all().annotate(latest_leg_date=Max('tradeleg__date'))

Upvotes: 4

Related Questions