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.
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'))
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With