django,mypy:查询集,选择。错误:不兼容的类型
Posted
技术标签:
【中文标题】django,mypy:查询集,选择。错误:不兼容的类型【英文标题】:django, mypy : queryset, choices. error: Incompatible types 【发布时间】:2021-06-02 08:24:46 【问题描述】:我们有:
在models.py中
class Language(models.IntegerChoices):
en = 1
ru = 2
class Translation(models.Model):
language_id = models.PositiveIntegerField(choices=Language.choices)
mnemonic = models.CharField(max_length=255)
translation = models.CharField(max_length=255)
-
在 serializers.py 中
66 def get_translations(self, obj):
67 language: int = self.initial_data.get('language') or settings.SERVER['current_language_id']
68 common_public = Translation.objects.filter(language_id=language).exclude(mnemonic__startswith='dictionary')
当我通过 mypy 检查时:
resources/serializers.py:67: 错误:赋值类型不兼容(表达式类型为“Union[Any, object]”,变量类型为“int”)
-
如果在 serializers.py 中
66 def get_translations(self, obj):
67 language: Union[Any, object] = self.initial_data.get('language') or settings.SERVER['current_language_id']
68 common_public = Translation.objects.filter(language_id=language).exclude(mnemonic__startswith='dictionary')
通过mypy检查:
resources/serializers.py:68: 错误:查找“language_id”的类型不兼容:(得到“Union[Any, object]”,预期为“Union[str, int]”)
3)
66 def get_translations(self, obj):
67 language: Union[str, int] = self.initial_data.get('language') or settings.SERVER['current_language_id']
68 common_public = Translation.objects.filter(language_id=language).exclude(mnemonic__startswith='dictionary')
检查一下:
resources/serializers.py:67:错误:赋值类型不兼容(表达式类型为“Union[Any, object]”,变量类型为“Union[str, int]”)
怎么了?
mypy.ini:
[mypy]
python_version = 3.8
mypy_path = ./stubs
check_untyped_defs = True
disallow_any_generics = True
disallow_untyped_calls = True
disallow_untyped_decorators = True
ignore_errors = False
ignore_missing_imports = True
implicit_reexport = False
strict_optional = True
strict_equality = True
no_implicit_optional = True
warn_unused_ignores = True
warn_redundant_casts = True
warn_unused_configs = True
warn_unreachable = True
warn_no_return = True
plugins = mypy_django_plugin.main
[mypy.plugins.django-stubs]
django_settings_module = server.settings
[mypy-*.migrations.*]
ignore_errors = True
【问题讨论】:
您是否注意到错误#1 指向第67 行,而错误#2 指向第68 行? self.initial_data.get 和 settings.SERVER 返回相同的东西吗? 是的。 self.initial_data.get 和 settings.SERVER 返回相同的整数。问题的关键是 IntegerChoises 中的一种类型是整数,另一种类型是整数 【参考方案1】:错误在settings.SERVER['current_language_id']
正确的方法:
getattr(settings.SERVER, 'current_language_id')
现在 mypy 好了
【讨论】:
以上是关于django,mypy:查询集,选择。错误:不兼容的类型的主要内容,如果未能解决你的问题,请参考以下文章
mypy 错误:返回值类型不兼容(得到“object”,预期“Dict [Any, Any]”)