Home > Software design >  Django Filter by ForeignKey value
Django Filter by ForeignKey value

Time:10-21

Suppose I have two models

class DocumentType(BaseModel):
    name = models.CharField(max_length=128)
    code = models.CharField(max_length=128)
    exp_days = models.PositiveIntegerField("Remind me before (Days)", blank=True, null=True)

    def __str__(self):
        return str(self.name)


class Document(BaseModel):
    type = models.ForeignKey("masters.DocumentType", on_delete=models.PROTECT)
    date_of_expiry = models.DateField(blank=True, null=True)
    attachment = models.FileField(blank=True, null=True)
    
    def __str__(self):
        return str(self.employee)

I need to get the documents that will expire in the next {exp_days} mentioned in the type.

documents = Document.objects.filter(date_of_expiry__lte=today timedelta(days=30))

The above filter will return the documents expiring in the next 30 days. But how to apply the exact same condition mentioned above

CodePudding user response:

You can use F() object that represents the value of a model field. so to reference exp_days from related model you can use F('type__exp_days')

An answer from Lutz Prechelt shows how to move the F() expression outside the timedelta.

Here is the modified code

from django.db.models import F

documents = Document.objects.filter(date_of_expiry__lte=today timedelta(days=1)*F('type__exp_days'))

As mentioned here, this will work with PostgreSQL but, might not with other DBs (Not confirmed).

  • Related