Home > Software design >  Django SQL: related tables, use latest() on field of parent table
Django SQL: related tables, use latest() on field of parent table

Time:11-11

Using .latest() on related tables, does the double-underscore syntax for related tables work?

class OrderHeader(models.model):
    order_id = models.CharField(unique=True,max_length=100)
    last_modified = models.DateField()

class OrderLine(models.model):
    line_nbr = models.IntegerField(unique=True)
    order = models.ForeignKey(OrderHeader,on_delete=models.Cascade)

class RefundLine(models.model):
    line_nbr = models.IntegerField(unique=True)
    order = models.ForeignKey(OrderHeader,on_delete=models.Cascade)
    refund_type = models.IntegerField(default=1)

How do I find the last_modified of RefundLine where refund_type = 1?

I can not make head or tail of the django documentation. My guess

RefundLine.objects.filter(refund_type=1).latest(order__last_modified)

results in an error order__last_modified is not defined

PS What is latest()? A synonym for Max()?

CodePudding user response:

try:

RefundLine.objects.filter(refund_type=1).latest('order__last_modified')

You have forgotten single quotes .

latest() gives you the last modified value. or you can try order_by('-id') it also gives you the last value.

  • Related