Reputation: 321
I am unable to calculate total time duration . Here Videos have durations, which is DurationField(). I am confusing about how to calculate total time duration from all videos.
Model
class VideoDetails(BaseModel, Timestamps, SoftDelete):
video_name = models.CharField(max_length=254, null=False, blank=False)
video_about_text = models.CharField(max_length=254, null=False, blank=False)
duration = models.DurationField()
video = models.OneToOneField(Video, on_delete=models.CASCADE)
class CourseModuleVideos(Timestamps, SoftDelete):
module_id = models.ForeignKey(CourseModule, on_delete=models.CASCADE)
video_id = models.ForeignKey(Video, on_delete=models.CASCADE)
class Video(BaseModel, Timestamps, SoftDelete):
create_date = models.DateTimeField(auto_now_add=True, null=True)
view
z = CourseModuleVideos.objects.filter(module_id=o)
for zo in z:
print('o', zo.video_id)
x = VideoDetails.objects.filter(video=zo.video_id).aggregate(sum('duration'))
print(x.duration)
Thre is an error
"unsupported operand type(s) for +: 'int' and 'str'"
Give me a solution to overcome this problem.
Upvotes: 1
Views: 342
Reputation: 477318
You should work with a Sum
expression [Django-doc], not with the builtin function [Python-doc]. You thus can implement this with the sum
Sum
, and access the value in the dictionary with x['duration']
from django.db.models import Sum
# ⋮
x = VideoDetails.objects.filter(video=zo.video_id).aggregate(
Sum('duration')
)
print(x['duration'])
This is however not very efficient, since you will calculate the duration of each VideoDetails
separately, and thus for N videos, make N queries.
We can calculate the sum of the entire module with:
VideoDetails.objects.filter(
video__coursemodulevideos__module_id=o
).aggregate(sum('duration'))['duration'] or timdelta()
Upvotes: 1