简体   繁体   English

Django 查询集按字段排序

[英]Django queryset ordering by fields

i'm using django 2 and in my list view i want to oder the queryset by likecount and datetime field.我正在使用 django 2 并且在我的列表视图中我想通过 likecount 和 datetime 字段对查询集进行排序。 The main goal is to odering the post with mostlikes for today.主要目标是在今天获得最多赞的帖子。 Like, i want to show the most liked posts for today.就像,我想显示今天最喜欢的帖子。 It's like todays top 10 post(mostliked) .就像今天的前 10 个帖子(最喜欢) i have tried many ways but can't figure it out.我尝试了很多方法,但无法弄清楚。 I hope you guys can help me.我希望你们能帮助我。

My models.py:我的模型.py:

class post(models.Model):
    parent = models.ForeignKey("self", on_delete=models.CASCADE, blank=True, null=True)
    title = models.CharField(max_length=100)
    image = models.ImageField(upload_to='post_pics', null=True, blank=True)
    content = models.TextField()
    likes = models.ManyToManyField(User, related_name='likes', blank=True)
    date_posted = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    restrict_comments = models.BooleanField(default=False)
    watchlist = models.ManyToManyField(User, related_name='watchlist', blank=True)

    def __str__(self):
        return self.content

    class Meta:
        ordering = ['-date_posted', 'title']

    def get_absolute_url(self):
        return reverse ('blog-home')

    def total_likes(self):
        return self.likes.count()

My views.py:我的意见.py:

@login_required
def most_likes(request):
    posts = post.objects.annotate(like_count=Count('likes')).order_by('-like_count', '-date_posted')
    context = {'posts': posts}

    return render(request, 'blog/most_likes.html', context)

If I'm getting you right, you are already ordering your queryset by the fields you want ( like_count and date_posted ), but you're still missing the part of getting only the results for a desired time period.如果我说得对,您已经按照您想要的字段( like_countdate_posted )对查询集进行了排序,但是您仍然缺少仅获取所需时间段的结果的部分。

If this is the case, then what you're missing is to filter the queryset.如果是这种情况,那么您缺少的是过滤查询集。 You would need something like this (to get the posts of the last 10 days, ordered by their date and likes count):你需要这样的东西(获取最近 10 天的帖子,按日期和喜欢计数排序):

import datetime as dt


@login_required
def most_likes(request):
    delta = dt.timedelta(days=10)
    posts = post.objects.filter(date_posted__gt=(dt.datetime.now() - delta)) \
        .annotate(like_count=Count('likes')).order_by('-like_count', '-date_posted')
    context = {'posts': posts}

    return render(request, 'blog/most_likes.html', context)

Now, I would try to pass the value of the desired time period I want to filter the data as a query parameter, so I can do something as the following:现在,我将尝试将想要过滤数据的所需时间段的值作为查询参数传递,因此我可以执行以下操作:

delta = dt.timedelta(days=request.GET.get('days'))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM