gpt4 book ai didi

python (Django) : 'self.text' is unsubscriptable

转载 作者:行者123 更新时间:2023-12-04 14:11:58 25 4
gpt4 key购买 nike

我是按照《Django for beginners》这本书学习Django的,有个奇怪的问题。下面的代码片段确实有效,但 Pylint 一直向我显示错误,我知道错误发生了。但是作者什么也没做。请问有人知道为什么吗?代码片段来 self 的应用程序文件夹的 models.py。

from django.db import models

# Create your models here.
class Post(models.Model):
text = models.TextField()

def __str__(self):
return self.text[:50]

我的 vscode 编辑器中的 pylint 错误消息是 -值“self.text”不可订阅

我的环境:Win 10、Python 3.6、Django 3.0.1

最佳答案

The code snippet below actually works, but Pylint keeps showing me an error. Does anyone know why, please?

是的,因为 Pylint 不“理解”在模型和字段的元类中实现的逻辑。因此它认为 self.text 将返回 TextField 对象,这确实是不可订阅的。然而,元类将为 self.text注入(inject)”一个字符串。

有一个pylint-django package [pypi]这对 Django 的工作原理有了更好的理解,尽管它仍然是“有限的”。作为它列出的功能之一:

  • Fixes pylint’s knowledge of the types of Model and Form field attributes.

所以通常它会解决这个问题。尽管对于自定义模型字段,它可能仍然会失败。

关于 python (Django) : 'self.text' is unsubscriptable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63601269/

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