Django ORM data based on max date group
model
class quote(models.Model):
id = models.AutoField(primary_key=True)
stock = models.ForeignKey(stock, related_name='stock', on_delete=models.CASCADE)
price = models.DecimalField(max_digits=30,decimal_places=5)
valid_till = models.DateTimeField()
created_at = models.DateTimeField() #time
updated_at = models.DateTimeField(blank=True,null=True)
ex data
id stock price valid_till created_at
1. 1. 200. 09 April. 09 April
2. 1. 300. 10 April. 09 April
output desire
id stock price valid_till created_at
2. 1. 300. 10 April. 09 April
I need only record for max date of every stock
currently doing quote.objects.values('stock__symbol').annotate(max_date=Max('valid_till'))
but still not able to think about proper solution
Here are two methods to get the quote(s) with max date. Using that queryset you can then find whatever related model instances you need.
- Find max value using aggregate() method, then query filtering the max value
# returns a dict containing your max_date
aggregation = quote.objects.aggregate(max_date=Max('valid_till'))
# get max_date from dict
max_date = aggregation['max_date']
#filter quotes based on max_date
max_date_quotes = quote.objects.filter(valid_till = max_date)
- Order by valid_till. This assumes you have a single max date.
max_date_quote = quote.objects.all().order_by('-valid_till').first()