首页 > 解决方案 > 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中的评论

标签: djangodjango-modelsdjango-templates

解决方案



推荐阅读