“喜欢”字段是ManyToManyField,我希望按从“喜欢”到“最少”的顺序呈现帖子。 ... order_by(“-likes”)无效,我看不出为什么这是代码。我猜是因为这不是整数,但我不能只是... order_by(“-likes.count”),对吧?
views.py
def top_Post(request, id=None):
queryset_list = Post.objects.all().order_by("-likes")
paginator = Paginator(queryset_list, 10)
page = request.GET.get('page')
try:
queryset = paginator.page(page)
except PageNotAnInteger:
queryset = paginator.page(1)
except EmptyPage:
queryset = paginator.page(paginator.num_pages)
context = {
"object_list":queryset,
"title":"List",
}
return render(request, 'blog/top.html', context)
top.html
{% for obj in object_list %}
<div class="card border-success mb-3" style="max-width: 54rem;">
<div class="card-header bg-transparent border-success">{{
obj.user|truncatechars:12}} <br> <small>{{ obj.date|timesince }} ago</small>
</div>
<div class="card-body text-success">
<h5 class="card-title">{{ obj.title |truncatechars:13 }}</h5>
<p class="card-text">{{ obj.body|truncatechars:20 }}</p>
<a class="btn btn-outline-success" href="{{ obj.get_absolute_url }}"
role="button">Detail</a>
</div>
<div class="card-footer bg-transparent border-success">
{{obj.text_author|truncatechars:25 }}</div>
</div>
{% endfor %}
models.py
class Post(models.Model):
title = models.CharField(max_length=200)
body = models.TextField()
user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True)
date = models.DateTimeField(auto_now=True, auto_now_add=False)
likes = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name='post_likes')
text_author = models.CharField(max_length=200, null=True, blank=True)