[英]AttributeError at / 'dict' object has no attribute '_mptt_meta'
I try to build blog by using posts and MPTT comments, this will be in the home view www.mysite.com
that's mean I cann't pass pk to the url so I tried to get the post objects using for loop我尝试通过使用帖子和 MPTT 评论来构建博客,这将在主页视图
www.mysite.com
这意味着我无法将 pk 传递给 url 所以我尝试使用 for 循环获取帖子对象
comma = Post.objects.all()
comm = []
for post in comma:
comment = PostCommentIDF.objects.filter(post=post)
comm.append({"comme": comment}
context = {'comment': comm,}
return render(request, 'personal/home.html', context)
And my Mptt comment model还有我的 Mptt 评论 model
class PostCommentIDF(MPTTModel):
post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='pos_com')
parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='post_children')
author = models.ForeignKey(Account, on_delete=models.CASCADE)
content = models.TextField()
created_date = models.DateTimeField(auto_now_add=True)
status = models.BooleanField(default=True)
likes = models.ManyToManyField(Account, blank=True, related_name='pos_com')
My Post Model我的帖子 Model
class Post(models.Model):
author = models.ForeignKey(Account, on_delete=models.CASCADE)
article = models.TextField(null=True, blank=True)
photo_article = models.ImageField(max_length=255, upload_to=get_poster_filepath)
My mptt coments in the template模板中我的 mptt 评论
{% recursetree comment %}
<div id="{{ node.id }}" class="my-2 p-2" style="border: 0px solid grey">
<div class="d-flex justify-content-between">
{{ node.publish|naturaltime }}
<div class="node-content mt-3">{{ node.content }}</div>
</div>
</div>
{% endrecursetree %}
comment
in your template context is a list of dictionaries.模板上下文中的
comment
是字典列表。 It should be a list of PostCommentIDF
instances.它应该是
PostCommentIDF
实例的列表。 And you are doing multiple SQL queries which is really inefficient.而且您正在执行多个 SQL 查询,这确实效率低下。 use
__in
operator instead and use the queryset directly, it's iterable too:改用
__in
运算符并直接使用查询集,它也是可迭代的:
comma = Post.objects.all()
comment = PostCommentIDF.objects.filter(post__in=comma)
context = {'comment': comment,}
return render(request, 'personal/home.html', context)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.