Home > database >  How can we achive max of every stock valid date with foreign key name with ORM Django
How can we achive max of every stock valid date with foreign key name with ORM Django

Time:12-11

model

class stock(models.Model):
    id = models.AutoField(primary_key=True)
    symbol = models.CharField(max_length=30)
    name    = models.CharField(max_length=50)
    sector  = models.CharField(max_length=50,blank=True,null=True)
    validtill = models.DateTimeField()
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(blank=True,null=True)
class quote(models.Model):
    id = models.AutoField(primary_key=True)
    stock = models.ForeignKey(stock, related_name='quote', on_delete=models.CASCADE)
    valid_till = models.DateTimeField()
    ...

Current solution

quote.objects.values('valid_till').annotate(max_date=Max('valid_till')).values('stock','valid_till','price','created_at')

{'stock': 984, 'valid_till': datetime.datetime(2021, 12, 9, 19, 4, 16), 'max_date': datetime.datetime(2021, 12, 9, 19, 4, 16)}

getting the result from above query but only thing I want is get the stock symbol from foreign key table

instead of id I want foreign key table column value

CodePudding user response:

You must indicate the desired value of the relationship, for example:

quote.objects.values('valid_till').annotate(max_date=Max('valid_till')).values('stock__symbol','valid_till','price','created_at')

If you only put "stock" it returns the id of the relationship

  • Related