我正在创建一个论坛应用,并希望显示最新评论员的用户名(如屏幕截图所示):
但是我的信息有一些差距,到目前为止我的代码是:
class Forum(models.Model):
"""
Forum Model
"""
forum_author = models.ForeignKey(
Profile,
related_name='user_forums',
null=True,
blank=True,
on_delete=models.CASCADE
)
forum_title = models.CharField(
max_length=225,
verbose_name=u'Thread Title',
blank=False,
null=False
)
forum_category = models.ForeignKey(
'Category',
verbose_name=u'Thread Category',
)
forum_content = MarkdownxField()
class Comment(models.Model):
"""
Comment Model
"""
forum = models.ForeignKey(
'Forum',
related_name='forum_comments'
)
comment_author = models.ForeignKey(
Profile,
related_name='user_comments',
null=True,
blank=True,
on_delete=models.CASCADE
)
comment_content = MarkdownxField()
created_date = models.DateTimeField(
default=datetime.datetime.now,
)
...
from app_forum.models import Forum, Comment
def forum_list_view(request):
forum_list = Forum.objects.all().order_by("-misc_created")
return render(request, 'app_forum/forum_list.html' {'forum_list': forum_list})
我的单线程观点:
def forum_single_view(request, pk):
forum = get_object_or_404(Forum, pk=pk)
forum_comments = Comment.objects.filter(forum=forum.id)
paginator = Paginator(forum_comments, 10)
page = request.GET.get('page', 1)
try:
forum_comments = paginator.page(page)
except PageNotAnInteger:
forum_comments = paginator.page(1)
except EmptyPage:
forum_comments = paginator.page(paginator.num_pages)
return render(request, 'app_forum/forum_single.html', {'forum': forum, 'forum_comments': forum_comments})
答案 0 :(得分:1)
您可以通过
获取最新评论 L_comment = Comment.objects.latest('created_date')
您可以通过
获取评论用户 L_comment.comment_author
如果您想在特定论坛中获取最新评论,那么
forum = Forum.objects.get(forum_title='forum-title')
latest_comment = forum.forum_comments.latest('created_date')
author = latest_comment.comment_author
<强>更新强>
更好的选择是在论坛类中定义一个方法,如下所示:
def latest_comment_author(self):
return self.forum_comments.latest('created_at').comment_author
您可以通过
从模板访问它 {{ forum.latest_comment_author }}
答案 1 :(得分:1)
您可以使用相关的对象管理器。在论坛模型上创建一个方法,以检索论坛上的最新评论。类似的东西:
@cached_property
def latest_coment(self):
return self.forum_comments.order_by('-created_date').first()
然后,您可以在模板上调用此方法以获取最新评论