【发布时间】:2022-01-04 21:09:32
【问题描述】:
谁能解释一下,为什么我得到 Post.CommentPost.None?
如何在查询中正确连接 CommentPost 和 Posty?我需要得到 {{posty.cmets.user}} 我的结果是 Post.CommentPost.None
这里有一些关于我的模型和功能的信息。
class Posty(models.Model):
title = models.CharField(max_length=250, blank=False, null=False, unique=True)
sub_title = models.SlugField(max_length=250, blank=False, null=False, unique=True)
content = models.TextField(max_length=250, blank=False, null=False)
image = models.ImageField(default="avatar.png",upload_to="images", validators=[FileExtensionValidator(['png','jpg','jpeg'])])
author = models.ForeignKey(Profil, on_delete=models.CASCADE)
updated = models.DateTimeField(auto_now=True)
published = models.DateTimeField(auto_now_add=True)
T_or_F = models.BooleanField(default=False)
likes = models.ManyToManyField(Profil, related_name='liked')
unlikes = models.ManyToManyField(Profil, related_name='unlikes')
created_tags = models.ForeignKey('Tags', blank=True, null=True, related_name='tagi', on_delete=models.CASCADE)
test_wyswietlenia = models.IntegerField(default=0, null=True, blank=True)
class CommentPost(models.Model):
user = models.ForeignKey(Profil, on_delete=models.CASCADE)
post = models.ForeignKey(Posty, on_delete=models.CASCADE, related_name="comments")
content1 = models.TextField(max_length=250, blank=False, null=False)
date_posted = models.DateTimeField(default=timezone.now)
date_updated = models.DateTimeField(auto_now=True)
观看次数
tag = request.GET.get('tag')
if tag == None:
my_tag = Posty.objects.prefetch_related('comments')
my_view = Posty.objects.prefetch_related('my_wyswietlenia')
else:
my_tag = Posty.objects.filter(created_tags__tag=tag)
my_view = Posty.objects.prefetch_related('my_wyswietlenia')
模板
{% for post in my_tag %}
{% if post.comments.last.user == None %}
<span class="forum_tag_author">Komentarz » <a href="{% url 'home:detail_post' post.pk %}">Brak komentarza</a></span><br/>
<span class="forum_tag_author">Stworzony przez » <a href="{% url 'profile:profil_uzytkownika' post.pk %}">{{post.author}} </a> </span><hr/>
{% else %}
<span class="forum_tag_author">Komentarz » <a href="{% url 'home:detail_post' post.pk %}">{{post.comments.last.content1}}</a></span><br/>
<span class="forum_tag_author">Odpowiadający » <a href="{% url 'profile:profil_uzytkownika' post.pk %}">Dodany przez: {{post.comments.last.user}} </a> </span><hr/>
{% endif %}
{% endfor %}
还有这个 {{post.cmets}} 发出请求 Post.CommentPost.None
什么是问题?我做错了什么?
【问题讨论】:
-
.comments是经理,你可以使用{{ post.comments.all }},但我建议在视图中注释查询集以获得最后一个作者和content1更快。 -
当我这样做时,我得到了所有 cmets 列表。当我只需要时,帖子名称,最后一个帖子,添加最后评论到帖子的用户
-
当然,这就是您需要注释而不是预取的原因。
标签: django post django-queryset