Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

its possible to get months between two dates in django queryset?

I'm trying to get make a complete query set, and now all I need is get the months between two DateTime fields from my model, it's possible to do this action in a single query set. Im not talking about filter, cause in the model for example I have two datetimeField() and now what I want to do is, gets months between this dates.

like image 727
Rodrigo Espinoza Avatar asked Nov 04 '25 22:11

Rodrigo Espinoza


2 Answers

If your database supports DurationField you can go with ExtractMonth:

from django.db import models
from django.db.models.functions import ExtractMonth

queryset = MyModel.objects.annotate(
    diff=models.ExpressionWrapper(
        models.F('date1') - models.F('date2'), output_field=models.DurationField())
    ).annotate(months=ExtractMonth('diff'))
like image 153
Ivan Avatar answered Nov 06 '25 22:11

Ivan


The given answer didn't work for me on postgres because the diff field (DurationField) only support to Extract days function. ExtractMonth return "0".

Here the solution I've found :

queryset = MyModel.objects.annotate(
    months=(ExtractYear("date2") - ExtractYear("date1")) * 12 + (ExtractMonth("date2") - ExtractMonth("date1"))
)

Note that it only consider the difference between the first of each month and not an eventual fractional part given by the days. In this solution 2020-08-12 is considered as the same as 2020-08-01.

like image 23
fabien-michel Avatar answered Nov 06 '25 22:11

fabien-michel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!