【问题标题】:Cannot query "Cast object (1)": Must be "Person" instance无法查询“Cast object (1)”:必须是“Person”实例
【发布时间】:2018-05-27 18:57:21
【问题描述】:

我正在尝试创建我的演员的详细列表,其中将显示他曾担任演员的所有节目。这是tutorial 末尾的 Mozilla 挑战自己部分的一部分。

我在过滤我的 class Cast 时遇到问题,以便我可以获取特定的 Actor。

我不明白为什么过滤器不起作用。例如,如果 self.object 的值为 '3',它应该过滤掉所有的演员,只显示 id 为 3 的演员。但情况似乎并非如此。我也不理解它抛出的错误代码。我的 Cast 类确实有一个人的外键。

与我的节目详情页面类似,我希望它不是演员阵容,而是演员在电影中的主演。

Image of my Show Details Page

查看

class ActorDetailView(generic.DetailView):
    model = Cast
    template_name = 'show/actor-detail.html'

    def get_context_data(self, **kwargs):
        context = super(ActorDetailView, self).get_context_data(**kwargs)
        context['casts'] = Cast.objects.filter(person_id=self.object)

        return context

型号

class Person(models.Model):
    name = models.CharField(max_length=128)

    def __str__(self):
        return self.name

class Character(models.Model):
    name = models.CharField(max_length=128)
    on_which_show = models.ForeignKey('Show', on_delete=models.SET_NULL, null=True)
    def __str__(self):
        return self.name

class Cast(models.Model):
    person = models.ForeignKey(Person, on_delete=models.CASCADE)
    cast_show = models.ForeignKey('Show',on_delete=models.CASCADE)
    character = models.ForeignKey(Character, on_delete=models.CASCADE, null=True)

    def get_absolute_url(self):
        return reverse('actor-detail', args=[str(self.id)])


class Show(models.Model):
        title = models.CharField(max_length=200)
        genre = models.ManyToManyField(Genre, help_text='Select a genre for this book')
        language = models.ForeignKey('Language', on_delete=models.SET_NULL, null=True)
        summary = models.TextField(max_length=1000, help_text='Enter a brief description of the show', null=True)
        cast_of_the_show = models.ManyToManyField(Person,through='Cast')

        def __str__(self):
            return self.title

        def get_absolute_url(self):
            return reverse('show-detail', args=[str(self.id)])

【问题讨论】:

    标签: python django django-models django-views


    【解决方案1】:

    ActorDetailView 的模型应该是 Person 而不是 Cast。然后,您可以使用人员记录来获取他们所属的所有演员表。

    class ActorDetailView(generic.DetailView):
        model = Person
        template_name = 'show/actor-detail.html'
    
        def get_context_data(self, **kwargs):
            context = super(ActorDetailView, self).get_context_data(**kwargs)
            context['casts'] = Cast.objects.filter(person=self.object)
            return context
    

    【讨论】:

    • 感谢您抽出宝贵时间@warpri81。我很感激
    猜你喜欢
    • 2021-04-08
    • 2019-08-07
    • 2023-03-27
    • 1970-01-01
    • 2022-07-26
    • 2020-07-17
    • 1970-01-01
    • 1970-01-01
    • 2021-11-20
    相关资源
    最近更新 更多