首页 > 解决方案 > 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)

标签: djangodjango-views

解决方案


您正在all()直接调用posts模型的字段。不至于帖子的collection对象。基本上你是在调用你的类而不是你的实例。

请改为执行以下操作:

posts = collection.posts.all() #note the lower case

推荐阅读