查询字段值 - 返回未定义的全局名称

时间:2013-11-06 12:51:36

标签: django django-models django-queryset

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

我的模特:

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

我不确定为什么会收到这个错误?我认为我不需要创建模型字段的变量?

1 个答案:

答案 0 :(得分: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 =