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

2
  • check this out, let me know if that helps: stackoverflow.com/q/805393/9102309 Commented Jun 19, 2020 at 11:39
  • @Vedprakash Upraity actually it is not what i'm looking for Commented Jun 19, 2020 at 11:45

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.