python - 类函数对 self 的未解析引用

标签 python django

为什么我的 IDE 告诉我该行中有一个 Unresolved reference to self:

-->  photo = models.ImageField(upload_to=self.upload_path)

代码:

class Photo(models.Model):
    title = models.CharField(max_length=50, blank=True)
    album = models.ForeignKey(Album)
    photo = models.ImageField(upload_to=self.upload_path)
    upload = models.DateTimeField(auto_now_add=True)

    def upload_path(self, filename):
        title = self.album.title
        if " " in title:
            title.replace(" ", "_")
        return os.path.join(title, filename)

当我将 upload_path 函数放在类之外时,此错误不会出现。但是,我希望类中的函数尽量保持整洁。

没有 IDE 错误,但我不确定原因。

def upload_path(self, filename):
    title = self.album.title
    if " " in title:
        title.replace(" ", "_")
    return os.path.join(title, filename)


class Photo(models.Model):
    title = models.CharField(max_length=50, blank=True)
    album = models.ForeignKey(Album)
    photo = models.ImageField(upload_to=upload_path)
    upload = models.DateTimeField(auto_now_add=True)

最佳答案

self 只能在将其定义为参数的类方法中使用。

在这种情况下,您需要将该方法视为未绑定(bind)方法(无需为self 赋值),因为Django 本身会将实例作为第一个参数传入:

class Photo(models.Model):
    def upload_path(self, filename):
        ....

    photo = models.ImageField(upload_to=upload_path)

请注意,因为您在类定义本身内部使用 upload_path,所以用法必须在 upload_path 的定义之后。

编辑:

根据 this bug report , Django 的迁移系统在 Python 2.x 上有一个限制,这将导致它无法使用上面的代码,即使代码本身是正确的。您必须将函数放在类之外才能使用迁移。

The documentation状态:

If you are using Python 2, we recommend you move your methods for upload_to and similar arguments that accept callables (e.g. default) to live in the main module body, rather than the class body.

关于python - 类函数对 self 的未解析引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30418742/

相关文章:

Django:如何自定义密码提示列表

javascript - Google+ 登录 - 未捕获的安全错误

选择字段中的 Django 空标签 - 无查询集

python - 如何构建一个正则表达式来捕获由单个空格分隔的单词?

Python - 使用循环重命名目录中的所有文件

python - 如何在忽略索引的情况下使用 isin

python - 元组比较 'A' == ('A' ),如何避免这种情况?

python - Pandas:如何使用 align 将 pandas 栏的开头居中

Django:在保存覆盖中创建并保存另一个模型

python - Django:整数字段上的 order_by 和过滤器