How to display data in a given time range in Django?

Viewed 77

Sort films by number of comments

topMovie = Movie.objects.annotate(
            num_comments=Count('Comments')).order_by('-num_comments')

model.py:

class Movie(models.Model):
    Title = models.CharField(max_length=200)
    Year = models.CharField(max_length=25, blank=True)
    Rated = models.CharField(max_length=10, blank=True)

class Comment(models.Model):
    comment_text = models.CharField(max_length=200)
    movie_id = models.ForeignKey(
        Movie, on_delete=models.CASCADE, related_name='Comments')
    pub_date = models.DateTimeField(blank =True,default = now)

how to transfer the time frame to display this field

topMovie = Movie.objects.annotate(
            num_comments=Count('Comments')).order_by('-num_comments')

within the specified time frames

1 Answers

You can filter the comments with:

topMovie = Movie.objects.filter(
    Comments__pub_date__range=(start_timestamp, end_timestamp)
).annotate(
    num_comments=Count('Comments')
).order_by('-num_comments')

This will not contain any mtopMovies without Comments in the given window. You can use filter=… parameter [Django-doc] to also retrieve Movies with Comments outside the range:

from django.db.models import Q

topMovie = Movie.objects.annotate(
    num_comments=Count(
        'Comments',
        filter=Q(Comments__pub_date__range=(start_timestamp, end_timestamp))
    )
).order_by('-num_comments')
Related