为什么我的 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 上有一个限制,这将导致它无法使用上面的代码,即使代码本身是正确的。您必须将函数放在类之外才能使用迁移。
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/