gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 11:57:09 25 4
gpt4 key购买 nike

我尝试编写查询以从列表中过滤/排除某些对象,但出现错误。

我的模型:

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
我不知道为什么我会收到那个错误?我认为我不需要创建模型字段的变量?

最佳答案

在过滤查询中,您不需要 ==用于比较。

将您的 View 代码更新为

context['unused_benefits'] = Benefit.objects.filter(used_benefit__isnull=True).exclude((benefit_type = 'N')
context['nodeal_benefits'] = Benefit.objects.filter(benefit_type = 'N')
# ---------------------------------------------------------------^ single =

关于django - 查询字段值 - 返回未定义的全局名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19812599/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com