我需要在 Django 模板上显示消息。每条消息可以有 0 到多个评论。我需要显示每条消息的评论。但是,如果消息没有评论,那么它就是“无”,我无法对其进行迭代。该问题发生在 Django 模板中。
#models.py
class User(models.Model):
firstName = models.CharField(max_length = 255)
lastName = models.CharField(max_length = 255)
email = models.CharField(max_length = 255)
birthDate = models.DateField()
password = models.CharField(max_length = 255)
createdAt = models.DateTimeField(auto_now_add = True)
updatedAt = models.DateTimeField(auto_now = True)
objects = UserManager()
class Message(models.Model):
content = models.TextField()
user = models.ForeignKey(User, related_name = "messages")
createdAt = models.DateTimeField(auto_now_add = True)
updatedAt = models.DateTimeField(auto_now = True)
objects = UserManager()
class Comment(models.Model):
content = models.TextField()
message = models.ForeignKey(Message, related_name = "comments", default = [])
createdAt = models.DateTimeField(auto_now_add = True)
updatedAt = models.DateTimeField(auto_now = True)
objects = UserManager()
#views.py
#Main wall page
#Renders wall.html
def wall(request):
wallDict = {
"message" : Message.objects.all()
}
return render(request, "loginRegApp/wall.html", wallDict)
#wall.html
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<meta charset="utf-8">
</head>
<body>
<div class="container">
<a href="/logout">Log out</a>
<form action="message/create" method="post">
{% csrf_token %}
<h4>Post a message</h4>
<textarea name="message"></textarea>
<input type="submit" value="Post a message">
</form>
{% for message in messages %}
<div>
<h6>{{message.user.firstName}} {{message.user.lastName}} - {{message.createdAt}}</h6>
<p>{{message.content}}</p>
{% if message.comments %}
{% for comment in message.comments %}
<h6>Comment: {{message.user.firstName}} {{message.user.lastName}} - {{comment.createdAt}}</h6>
<p>{{comment.content</p>
{% endfor %}
{% endif %}
<form action="comment/{{message.id}}/create" method="post">
{% csrf_token %}
<textarea name="comment"></textarea>
<input type="submit" value="Post a comment">
</form>
</div>
{% endfor %}
</div>
</body>
</html>
我正在尝试显示所有评论,无论是 0 条还是 100 条。
您应该在模板中使用 .all
来访问包含注释的 QuerySet
。无需使用 {% if ... %}
和 {% endif %}
:
{% for comment in message.comments<b>.all</b> %}
<h6>Comment: {{message.user.firstName}} {{message.user.lastName}} - {{comment.createdAt}}</h6>
<p>{{comment.content</p>
{% endfor %}
在您看来,您可能想要使用.prefetch_related(..)
[Django-doc]此处以避免对每条消息进行额外的查询来获取相关评论,例如:
def wall(request):
wallDict = {
'message' : Message.objects.prefetch_related(
'comments', 'comments__user'
).all()
}
return render(request, 'loginRegApp/wall.html', wallDict)
我是一名优秀的程序员,十分优秀!