英文:
Django - VSCode does not recognize foreign key related names and gives error
问题
Post模型有一个外键指向User模型,其related name为posts
。
posts = user.posts.all()
^^^^^
Django显然工作正常。但是在VSCode中出现的错误很烦人。
如何让VSCode知道这不是一个错误?
英文:
Post model has a foreign key to User model with posts
as its related name.
posts = user.posts.all()
^^^^^
Django works fine obviously. But the error in VSCode is annoying.
How can I make VSCode know this is not an error?
答案1
得分: 1
以下是翻译好的代码部分:
这只是一个权宜之计,未来将会改进,但目前解决这个问题的方法是这样的(在mypy插件之外,即在VS Code内置的检查器中)。
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from django.db.models.manager import RelatedManager
class RelModel(Model):
belongs_to = models.ForeignKey(MyModel, related_name="things")
class MyModel(Model):
if TYPE_CHECKING:
things: RelatedManager[RelModel]
希望这对你有所帮助。如果有任何其他问题,请随时提出。
英文:
So this is a hack and will improve in the future, but this is the way to solve this right now (outside the mypy plugin, i.e in VS codes built in checker)
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from django.db.models.manager import RelatedManager
class RelModel(Model):
belongs_to = models.ForeignKey(MyModel, related_name="things")
class MyModel(Model):
if TYPE_CHECKING:
things: RelatedManager[RelModel]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论