Django ORM calculates the number of days between two dates

Scenario

I have a table student. it has the following attributes

name,

age,

school_passout_date,

college_start_date

I need a report to find out that a student is avg number of daysfree from going to school and elementary college.

Current approach

I am currently annoyed by the range of values ​​that determine the days for each student and receive them.

Problem

This is very inefficient when the record set becomes larger.

Question

Are there any abilities in ORM Django that give me summary days between two dates?

Opportunity

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'))

Best

+4
source share
3 answers

, () , , .

,

from django.db.models import Avg
avg_start_date = Students.objects.filter(school_passed=True, started_college=True).aggregate(Avg('school_start_date'))
avg_passout_date = Students.objects.filter(school_passed=True, started_college=True).aggregate(Avg('school_passout_date'))
avg_time_at_college = avg_passout_date - avg_start_date
+2

Django 4- : Max, Min, Count, et Average, .

extra. :

Students.objects.
    extra(select={'difference': 'school_passout_date' - 'college_start_date'}).
    filter('school_passed=True, started_college=True)

+1

, Django ORM .

F().

from django.db.models import Avg, F
college_students = Students.objects.filter(school_passed=True, started_college=True)
duration = college_students.annotate(avg_no_of_days=Avg( F('college_start_date') - F('school_passout_date') )
0

All Articles