python - + : 'DeferredAttribute' and 'str' 不受支持的操作数类型

标签 python django

我正在尝试通过管理员保存模型,但我不断收到此错误

unsupported operand type(s) for +: 'DeferredAttribute' and 'str'".

我想返回模型的字符串表示形式。

这是我尝试过的:

def __str__(self):
    return str(self.album_name + "" + self.artist)

我的模型:

class Album(models.Model):
    album_name = models.CharField(max_length=250,)
    album_logo = models.FilePathField(path='music/static/music/song_logo', 
    null=True, blank=True, recursive=True)
    artist = models.CharField(max_length=150)
    primaryid = models.AutoField(primary_key=True, null=False)

    @classmethod
    def __str__(self):
        return self.album_name + " " + self.artist

例如,我想要像“hilltop”这样的东西

最佳答案

__str__ 不应该是 classmethod,删除该装饰器将解决您的问题。

您将类 (Album) 作为 self 而不是实例传递给 __str__ 方法。请参阅this question了解详情。

关于python - + : 'DeferredAttribute' and 'str' 不受支持的操作数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55409044/

相关文章:

python - 如何为队列中的内容添加变量类型注释?

python - 尝试了 Django get_absolute_url NoReverseMatch 零模式

python - 可以从django开发服务器下载文件吗

python - 在 Windows 8 中编译 mod_wsgi 不适用于 django

python - Django + celery : ImportError: No module named project. 网址

python - Django - 如何覆盖每个语言环境的默认日期格式?

python - 使用 python 3.3 时是否需要 python 包 virtualenv?

python - 如何在python中将列表保存为numpy数组?

python - 超时调用 C 函数 - ctypes

python - 如何在 Django REST API 中使用 GPS 位置?