Django – VSCode不识别外键关联的名称并报错

huangapple go评论56阅读模式
英文:

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]

huangapple
  • 本文由 发表于 2023年2月6日 21:20:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/75361847.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定