Reputation: 590
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
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