如何从订阅特定用户的所有课程中获得所有法律?
class Law(models.Model):
name = models.CharField('Nome', max_length=100)
slug = models.SlugField('Atalho')
description = models.TextField('Description', blank = True, null=True)
class Course(models.Model):
name = models.CharField('Nome', max_length=100)
slug = models.SlugField('Atalho')
description = models.TextField('Descrição', blank = True, null=True)
laws = models.ManyToManyField(Law, related_name='law_course')
class Subscription(models.Model):
STATUS_CHOICES=(
(
(0, 'Pendente'),
(1, 'Approved'),
(2, 'Canceled'),
)
)
user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, verbose_name="Usuário", related_name="inscricao") #inscricao é criado no usuario
course = models.ForeignKey(Course, on_delete=models.CASCADE, verbose_name="Course", related_name="subscription")
status = models.IntegerField(
'Status', choices=STATUS_CHOICES, default = 0, blank=True
)
class Meta:
unique_together = (('user','course'))
因此,可以为用户订阅一门或多门课程。每门课程都有一个或多个法律。
我有一个页面,我需要列出如果已批准(status = 1
的订阅,则特定用户订阅的每个课程的所有法律。
例:
John用户已订阅了两门课程:课程A和课程B。
Course A laws: law1, law2, law3
Course B laws: law1, law20, law30
因此,当约翰登录时,我需要显示课程的法律和课程的名称:
law1 - Course A, Course B
law2 - Course A
law3 - Course A
law20 - Course B
law30 - Course B
请注意,我不能两次显示law 1
,但是我显示了包含该定律的每门课程。
我尽力而为。提前Tks
答案 0 :(得分:3)
您可以使用设置来存储法律(最终将是唯一的)。
laws_set = set()
subscriptions = Subscription.objects.filter(user=your_user, status=1)
对于每个订阅,请先学习该课程,然后获取与该课程相对应的所有法律。
for subscription in subscriptions:
laws = subscription.course.laws.all()
for law in laws:
laws_set.add(law)
现在,对于lawset中的每条法律,您都可以打印相应的课程。
for law in laws_set:
print(law.name, end='')
for course in law.law_course.all(): # Since law_course is the related name
print(course.name, end='')
print('\n')