python - 名称 'self' 未定义

标签 python django python-2.x

class customerDetailView(DetailView):
    queryset = Customer.objects.get(name=self.name) # This line give error NameError: name 'self' is not defined
    context_object_name = 'customerDetail'
    template_name = "customer.html"
    allow_empty = True

    def __init__(self, name=None, *args):
        self.name = name

报错 NameError: name 'self' is not defined

最佳答案

由于您想要自定义 DetailView 的查询集,正确的方法是覆盖 get_queryset() 函数。查看documentation for DetailView它显示了方法解析顺序。特别是,get_queryset()被称为。

所以你的代码会变成这样:

class customerDetailView(DetailView):
    context_object_name = 'customerDetail'
    template_name = "customer.html"
    allow_empty = True

    def __init__(self, name=None, *args):
        self.name = name

    def get_queryset(self):
        return Customer.objects.get(name=self.name)

你不能像现在这样使用 self 因为 self 在类声明中不存在,只有当类的实例已创建。

关于python - 名称 'self' 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14787163/

相关文章:

python - 如何使用 Django Rest 过滤器限制查询结果

python - Django 多对多关系不保存

python - 如何关闭组合框事件更改时的 GTK 对话?

python - 使用 python 借助命名空间创建 xml

Python计算字符串中不与字符串重叠的出现次数

python - 使用 python 和 GObject 在 glade 中添加组合框

python - 如何在 django 中对每个应用程序的用户进行身份验证

linux - 如何在 Linux 中获取所有插入设备的 USB ID

json - 类型错误 : <object> is not JSON serializable

python - 基于 Spacy 规则的匹配来识别 python 中与金钱/日期相关的单词