要按照日期对博客文章评论进行排序,可以使用Django的ORM查询,并使用.order_by()
方法按照日期字段进行排序。
以下是一个示例解决方案:
from django.db import models
class Blog(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
class Comment(models.Model):
blog = models.ForeignKey(Blog, on_delete=models.CASCADE, related_name='comments')
text = models.TextField()
date = models.DateTimeField(auto_now_add=True)
from django.shortcuts import render
from .models import Blog
def blog_detail(request, blog_id):
blog = Blog.objects.get(id=blog_id)
comments = blog.comments.order_by('-date') # 按照评论日期倒序排序
return render(request, 'blog_detail.html', {'blog': blog, 'comments': comments})
{{ blog.title }}
{{ blog.content }}
Comments:
{% for comment in comments %}
{{ comment.text }}
{{ comment.date }}
{% endfor %}
这样,你就可以按照评论日期对博客文章评论进行排序并在模板中显示它们了。
下一篇:按照日期排序不如预期