django - comment_set.all 如何用于从不存在的模型中获取数据?
问题描述
在 HTML 中,comment_set.all 用于从不存在的模型中获取数据。这背后是什么概念。
post_detail.html
{% extends "base.html" %}
...
<div>
{{ instance.comment_set.all }}
</div>
...
输出
[<Comment: User_Name >]
支持这一点的代码
评论应用模型如下
评论/models.py
from django.conf import settings
from django.db import models
# Create your models here.
from posts.models import Post
class Comment(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
post = models.ForeignKey(Post)
content = models.TextField()
timestamp = models.DateTimeField(auto_now_add=True)
def __str__(self):
return str(self.user.username)
帖子/模型.py
...
class Post(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
title = models.CharField(max_length=120)
slug = models.SlugField(unique=True)
image = models.ImageField(upload_to=upload_location,
null=True,
blank=True,
width_field="width_field",
height_field="height_field")
height_field = models.IntegerField(default=0)
width_field = models.IntegerField(default=0)
content = models.TextField()
draft = models.BooleanField(default=False)
publish = models.DateField(auto_now=False, auto_now_add=False)
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
objects = PostManager()
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("posts:detail", kwargs={"slug": self.slug})
class Meta:
ordering = ["-timestamp", "-updated"]
def get_markdown(self):
content = self.content
markdown_text = markdown(content)
return mark_safe(markdown_text)
...
帖子/views.py
...
def post_detail(request, slug=None):
instance = get_object_or_404(Post, slug=slug)
if instance.publish > timezone.now().date() or instance.draft:
if not request.user.is_staff or not request.user.is_superuser:
raise Http404
share_string = quote_plus(instance.content)
context = {
"title": instance.title,
"instance": instance,
"share_string": share_string,
}
return render(request, "post_detail.html", context)
...
请注意,在 views.py 中,posts_detail.html 是通过 post_detail() 呈现的,但是在 posts_detail.html 中,我们正在访问其中的评论数据。这是怎么可能的,因为posts/models.py中没有外键到comments/models.py中的评论
解决方案
推荐阅读
- mysql - 分页以及如何将所有可能的选项与数据库搜索结果一起返回?
- python-3.x - 我制作了一个游戏,其中方块掉落,您必须躲避它,但无法正确设置碰撞箱
- python-3.x - 计算条件概率
- javascript - 斐波那契问题,超过int的最大值
- excel - 使用多个匹配条件查找最近的数字索引 + 匹配 +min + abs
- sml - 如何在退出程序之前等待并发 ML 线程完成?
- linux - xprop:理解 set 命令
- c++ - How to debug Fiware-Orion
- javascript - 如何使用 Firetore 集合让我的个人资料名称出现在我的仪表板上?
- firefox - 如何仅删除一个表单自动完成值