django - Django 错误:'ManyToManyDescriptor' 对象没有属性 'all'
问题描述
我收到这个错误。我正在尝试遍历帖子以显示属于集合的帖子。我应该把它改成什么?
相关资料:
模型.py
class Collection(models.Model):
posts = models.ManyToManyField(Post, related_name='collection_posts', null=True, blank=True)
视图.py
def collection_detail_view(request, pk):
collection = Collection.objects.get(id=pk)
posts = Collection.posts.all() #this is the error
context = {
'collection': collection,
'posts': posts
}
return render(request, 'collection_detail.html', context)
解决方案
您正在all()
直接调用posts
模型的字段。不至于帖子的collection
对象。基本上你是在调用你的类而不是你的实例。
请改为执行以下操作:
posts = collection.posts.all() #note the lower case
推荐阅读
- java - 如何获取 java 对象的字段类型和值?
- wix - Wix 安装程序 - 安装到映射的网络驱动器时出现问题
- render - Ant design Table 不会使用 Nextjs 重新渲染
- machine-learning - 了解 LSTM 架构中的密集层(标签和 logits)
- xamarin - 用户在应用程序中崩溃。我不明白是什么原因
- python - 也是第二个字符串中的子字符串的最长前缀
- c# - 捕获字符串并将其作为列表传递给参数
- python - 在 Django 中使用 Textfield 和 charfield 模型时出错
- javascript - 如何为 p5js 创建动画类库
- javascript - 如何添加对特定消息的反应?