使用相关名称时出现问题

问题描述 投票:0回答:1

这是课程和学习者课程模型:

class Course(BaseModel, Timestamps, SoftDelete):
    name = models.TextField(_("Course Name"), max_length=100,
                            blank=True, null=True, unique=False)
    description = models.TextField(
        _("Course Description"), blank=True, null=True)
    course_number = models.CharField(
        max_length=15, null=True, blank=True, unique=True)....

class LearnerCourse(BaseModel, Timestamps, SoftDelete):
    course = models.ForeignKey(Course, verbose_name=_("Course"), on_delete=models.CASCADE, db_index=True, related_name='course_learner_courses')
    learner = models.ForeignKey(Learner, verbose_name=_("Learner Course"), on_delete=models.CASCADE, db_index=True)
    course_subscription = models.ForeignKey(CourseSubscription, null=True, on_delete=models.CASCADE, db_index=True)
    enroll_date = models.DateTimeField(verbose_name=_("Course Enroll Date"))
    is_favourite = models.BooleanField(default=False)

    

在 LearnerCourse 中使用了课程字段的相关名称,之后 当这样使用时

    details = LearnerCourse.objects.filter(learner=learner_id).all().order_by('-datetime_created')    
    print("details", details)   
    courses = details.course_learner_courses.all()  
    print("courses", courses)   

这会导致错误“SafeDeleteQueryset”对象没有属性“course_learner_courses” 请给我一些建议来解决这个问题。

python django django-models django-rest-framework
1个回答
0
投票

您应该迭代

details
查询集来访问每个单独的
LearnerCourse
实例,然后检索相关课程。这是更新的代码:

details = LearnerCourse.objects.filter(learner=learner_id).all().order_by('-datetime_created')    

# Iterate through each LearnerCourse instance in the queryset
for learner_course in details:
    courses = learner_course.course_learner_courses.all()  
    print("courses for LearnerCourse ID {}: {}".format(learner_course.id, courses))

从上面的代码中,我们迭代

LearnerCourse
查询集中的每个
details
实例,然后使用
learner_course.course_learner_courses.all()
访问相关课程。这应该可以解决您面临的问题。

© www.soinside.com 2019 - 2024. All rights reserved.