admin管理员组文章数量:1410724
I'm encountering a type checking error in VSCode with Pylance (pyright) when accessing serializer.validated_data["code"]
in a Django project. The errors are:
"__getitem__" method not defined on type "empty" Pylance
Object of type "None" is not subscriptable Pylance
The property type is inferred as:
(property) validated_data: empty | Unknown | dict[Unknown, Unknown] | Any | None
VSCode settings:
"python.languageServer": "Pylance",
"python.analysis.typeCheckingMode": "basic"
I've defined the serializer class like,
class InputSerializer(BaseSerializer):
code = serializers.CharField(
required=True,
max_length=255,
validators=[voucher_code_validator],
)
How can I fix this?
I'm encountering a type checking error in VSCode with Pylance (pyright) when accessing serializer.validated_data["code"]
in a Django project. The errors are:
"__getitem__" method not defined on type "empty" Pylance
Object of type "None" is not subscriptable Pylance
The property type is inferred as:
(property) validated_data: empty | Unknown | dict[Unknown, Unknown] | Any | None
VSCode settings:
"python.languageServer": "Pylance",
"python.analysis.typeCheckingMode": "basic"
I've defined the serializer class like,
class InputSerializer(BaseSerializer):
code = serializers.CharField(
required=True,
max_length=255,
validators=[voucher_code_validator],
)
How can I fix this?
Share Improve this question edited Mar 13 at 15:13 Daraan 4,2427 gold badges22 silver badges47 bronze badges asked Mar 11 at 9:35 FarhadFarhad 3361 gold badge2 silver badges16 bronze badges 1 |1 Answer
Reset to default 1This depends a bit on the stubs you are using. With (mypy) https://github/typeddjango/djangorestframework-stubs you should not get that error as validated_data
is typed as Any
. I would think there could be an equivalent for pyright (which Pylance uses).
With other (no?) stubs there are multiple possibilities, i.e. the ones you have listed empty | Unknown | dict[Unknown, Unknown] | Any | None
. To satisfy a type-checker you have to handle empty | None
. You could for example add these lines:
assert serializer.validated_data is not None
assert serializer.validate_data is not empty # import from fields
OR you assure that you indeed have a dict here:
assert isinstance(serializer.validated_data, dict)
Alternatives:
- write your own
validated_data
property with a more precise return type (and possible checks). - Unsafe but fastest way: Use
typing.cast
版权声明:本文标题:python - How to resolve type checking error in Django when accessing Serializer.validated_data - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744804232a2626047.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
serializer.validated_data.get("product")
the error is: "Argument of type "Unknown | Any | None" cannot be assigned to parameter". – Farhad Commented Mar 11 at 11:58