Django 按主页中最高点赞数排序
Posted
技术标签:
【中文标题】Django 按主页中最高点赞数排序【英文标题】:Django order by highest number of likes in homepage 【发布时间】:2021-01-28 19:39:21 【问题描述】:我正在尝试创建一个页面,人们可以在主页上看到评分最高的文章,但我不知道如何使用喜欢来做到这一点。
我的帖子模型
class Post(models.Model):
title = models.CharField(max_length=225)
post_image = models.ImageField(null=True, blank=True, upload_to="images/")
author = models.ForeignKey(User, on_delete=models.CASCADE)
body = models.TextField()
post_date = models.DateField(auto_now_add=True)
likes = models.ManyToManyField(User, related_name='blog_posts')
def total_likes(self):
return self.likes.count()
def __str__(self):
return self.title + ' | ' + str(self.author)
def get_absolute_url(self):
return reverse('post-detail', args=(str(self.id)),)
我的意见.py
def LikeView(request, pk):
post = get_object_or_404(Post, id=request.POST.get('post_id'))
liked = False
if post.likes.filter(id=request.user.id).exists():
post.likes.remove(request.user)
liked = False
else:
post.likes.add(request.user)
liked = True
return HttpResponseRedirect(reverse('post-detail', args=[str(pk)]))
class HomeView(ListView):
model = Post
template_name = 'home.html'
class PostDetail(DetailView):
model = Post
template_name = 'post_detail.html'
def get_context_data(self, *args, **kwargs):
context = super(PostDetail, self).get_context_data()
current_post = get_object_or_404(Post, id=self.kwargs['pk'])
total_likes = current_post.total_likes()
liked = False
if current_post.likes.filter(id=self.request.user.id).exists():
liked = True
context['total_likes'] = total_likes
context['liked'] = liked
return context
提前致谢! ..................................................... ..................................................
【问题讨论】:
这能回答你的问题吗? Django order by highest number of likes 【参考方案1】:As anoop quoted 你的HomeView
将是:
class HomeView(ListView):
queryset = Post.objects.annotate(like_count=Count('likes')).order_by('-like_count')
template_name = 'home.html'
context_object_name = 'post_list' # Providing a useful context_object_name is always a good idea
在您的模板中:
% for post in post_list %
【讨论】:
我尝试了代码,但似乎没有任何反应。它没有显示错误,但什么也不做 尝试从 shell 执行查询。它会起作用的。您在 db 中有 post 对象吗? 对不起,我是新人。如何从 shell 执行查询? python manage.py shell 。在运行 python manage.py runserver 的路径中运行此命令。执行 > from .models import Post (appname/projectnname.models) > posts = Post.objects.annotate(like_count=Count('likes')).order_by('-like_count') > 帖子。您可以看到帖子查询集,无论它是充满帖子对象还是空查询集以上是关于Django 按主页中最高点赞数排序的主要内容,如果未能解决你的问题,请参考以下文章