我有以下型号:
class Work_Music(MPTTModel, Work):
name = models.CharField(max_length=10, null=True, blank=True)
key = models.CharField(max_length=10, null=True, blank=True)
tonality = models.CharField(max_length=20, null=True, blank=True)
class WorkCast(models.Model):
work = models.ForeignKey(Work_Music, verbose_name=_('work'), related_name='workcast', null=True, blank=True, on_delete=models.PROTECT)
cast = models.ManyToManyField(Cast, verbose_name=_('cast'), related_name='workcast', blank=True)
order = models.DecimalField(max_digits=100, decimal_places=2, null=True, blank=True)
class Cast(models.Model):
name = models.CharField(max_length=100, null=True, blank=True)
在view.py中,我在模板上下文中发送以下内容:
work = Work_Music.objects.get(work=self.kwargs['pk'])
如何通过Work_Music对象访问WorkCast?
如何在模板中显示
Cast #1, Cast #2, Cast #3, Cast #4
如何吸引所有演员?是吗?
work.workcast.cast.all()
不产生任何输出。
如何将其显示为列表,中间用逗号分隔?
答案 0 :(得分:0)
我认为您是在django中引用反向模型引用_set
。您可以找到更多信息here。在您的情况下,您会做类似的事情,
work_music = WorkMusic.object.get(pk=1)
work_music.workcast_set.all() # would get you all workcast related to that work music object
希望这会有所帮助!