0

I have created model with procedure that subtract two dates from fields in model returning days difference between them, for example:

class Example:
    earlierDate=models.DateField()
    laterDate=models.DateField()

    def day_diff(self):
        return (laterDate-earlierDate).days

Is it possible to query database including day_diff procedure ?

in_views_query=Example.objects.filter(day_diff__gte=30)

When i use this kind o query it shows me that there is no field 'day_diff'

Regards

admfotad
  • 197
  • 3
  • 11

1 Answers1

2

You can use ExpressionWrapper to make this happen

from django.db.models import DateField, ExpressionWrapper, F

Example.objects.annotate(day_diff=ExpressionWrapper(
                F('laterDate') - F('earlierDate'), output_field=models.DateField()
))

Django also has a similar example in docs. check it out: https://docs.djangoproject.com/en/3.0/ref/models/expressions/#using-f-with-annotations

minglyu
  • 2,958
  • 2
  • 13
  • 32