Django Filter by ForeignKey value

Question:

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)

How can I retrieve documents with expiry dates that match a specified number of days (represented by {exp_days}) from today? I have a filter like this for documents expiring in the next 30 days:

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

How can I adapt this filter to match the number of days specified by {exp_days}?

Asked By: ANFAS PV

||

Answers:

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).

Answered By: Asad Mahmood