我正在尝试建立一个单一的课程平台,在那里我将只保存课程单元材料,只有有会员资格的人才能看到它,但是当我尝试检索Lesson.course_allowed_mem_types.all()
时,我遇到了以下错误'ManyToManyDescriptor' object has no attribute 'all'
,我如何修复这个简单的错误
class Lesson(models.Model):
content_title = models.CharField(max_length=120)
content_text = models.CharField(max_length=200)
thumbnail = models.ImageField(upload_to='static/xxx/xxx/xxx/xxx')
link = models.CharField(max_length=200, null=True)
allowed_memberships = models.ManyToManyField(Membership)
def __str__(self):
return self.content_title
观点
def get_context_data(self, **kwargs):
context = super(bootCamp, self).get_context_data(**kwargs)
context['lessons'] = Lesson.objects.all()
user_membership = UserMembership.objects.filter(user=self.request.user).first()
user_membership_type = user_membership.membership.membership_type
course_allowed_mem_types = Lesson.allowed_memberships.all()
context['course_allowed_mem_types'] = course_allowed_mem_types
return context
我想,, 一节课可能有很多会员。因此,您正在选择具有所有成员资格的所有课程
Lesson.allowed_memberships.all()
尝试选择单个课程,然后检索关联的成员
lesson = Lessons.objects.filter(pk=1)
course_allowed_mem_types = lesson.allowed_memberships.all()
如果您想创建自定义的类似列表的类型,最好从
collections.abc.Iterable
继承。它提供了处理此类容器类型所需的常见操作。 不能只对任何对象/类型调用.all()
,该类型定义实际上必须在类或父类中定义all()
方法例如
只能查询模型实例的多对多相关字段,不能查询模型类。究竟什么是“一个课程类的所有具体允许成员身份对象”(^{)
是“与任何现有课程对象相关的所有成员资格对象”,还是“与课程对象相关的所有成员资格对象”
这些是不同的查询,
Lesson.allowed_memberships.all()
也不意味着这是不正确的用法如果你想要前者,像这样的东西可能会奏效
(您已经将其作为
context['lessons']
使用,只需显示想法)相关问题 更多 >
编程相关推荐