I have a table student
. it has following attributes
name
,
age
,
school_passout_date
,
college_start_date
I need a report to know what is the avg number of days
student get free between the passing the school and starting college.
Currently i am irritating over the range of values finding days for each student and getting its avg.
That is highly inefficient when the record set gets bigger.
Is there any ability in the Django ORM that gives me totals days between the two dates?
I am looking for something like this.
Students.objects.filter(school_passed=True, started_college=True).annotate(total_days_between=Count('school_passout_date', 'college_start_date'), Avg_days=Avg('school_passout_date', 'college_start_date'))
You can simply subtract a date or datetime from each other, to get the number of days between them: This returns a timedelta object, which contains days, seconds and microseconds and represents the duration between any two date / time or datetime objects.
To calculate your data in the month format, you need to add the letter m as an argument at the end of your formula. Follow this format to calculate the days between two dates in months: The function will extract data from the referred cells to calculate the difference in months. You can also count the days between two dates in years.
Finally, return the difference between the two counts. Python comes with an inbuilt datetime module that helps us to solve various datetime related problems. In order to find the difference between two dates we simply input the two dates with date type and subtract them, which in turn provides us the number of days between the two dates.
We'll be using the built-in datetime package, that allows you to really easily work with datetime objects in Python. As datetime is a built-in module, you can access it right away by importing it at the top of your Python file. You can construct datetime objects in a few different ways:
You can do this like so:
Model.objects.annotate(age=Cast(ExtractDay(TruncDate(Now()) - TruncDate(F('created'))), IntegerField()))
This lets you work with the integer value, eg you could then do something like this:
from django.db.models import IntegerField, F
from django.db.models.functions import Cast, ExtractDay, TruncDate
qs = (
Model
.objects
.annotate(age=Cast(ExtractDay(TruncDate(Now()) - TruncDate(F('created'))), IntegerField()))
.annotate(age_bucket=Case(
When(age__lt=30, then=Value('new')),
When(age__lt=60, then=Value('current')),
default=Value('aged'),
output_field=CharField(),
))
)
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