4

我试着写一个查询来过滤/排除列表中的一些对象,但我得到一个错误。

我的模型:

class Benefit(TimeStampedModel):
    DEAL = 'D'
    NODEAL = 'N'

    TYPE_CHOICES = (
        (NODEAL, 'Does not need any signed deal'),
        (DEAL, 'Needs a signed deal'),
    )

    name = models.CharField(max_length=200)
    benefit_type = models.CharField(max_length=1, choices=TYPE_CHOICES, default=DEAL)    



class Profile(models.Model):
    user = models.OneToOneField(User)
    benefits = models.ManyToManyField(Benefit, verbose_name="Used benefits", blank=True, null=True, related_name="used_benefit")

我的观点:

class ProfilePage(TemplateView):
    template_name = "profile/frontpage.html"

    def get_context_data(self, **kwargs):
            context = super(ProfileFrontpage, self).get_context_data(**kwargs)
            context['unused_benefits'] = Benefit.objects.filter(used_benefit__isnull=True).exclude(benefit_type=='N')
            context['nodeal_benefits'] = Benefit.objects.filter(benefit_type=='N')
            return context

但它不起作用。我收到此错误:global name 'benefit_type' is not defined

我不确定为什么会出现该错误?我不认为我需要为模型字段创建一个变量?

4

1 回答 1

5

在过滤查询中,您不需要==进行比较。

将您的视图代码更新为

context['unused_benefits'] = Benefit.objects.filter(used_benefit__isnull=True).exclude((benefit_type = 'N')
context['nodeal_benefits'] = Benefit.objects.filter(benefit_type = 'N')
# ---------------------------------------------------------------^ single =
于 2013-11-06T12:55:57.007 回答