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

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

Django - VSCode does not recognize foreign key related names and gives error

问题

Post模型有一个外键指向User模型,其related name为posts

  1. posts = user.posts.all()
  2. ^^^^^

Django显然工作正常。但是在VSCode中出现的错误很烦人。
如何让VSCode知道这不是一个错误?

英文:

Post model has a foreign key to User model with posts as its related name.

  1. posts = user.posts.all()
  2. ^^^^^

Django works fine obviously. But the error in VSCode is annoying.
How can I make VSCode know this is not an error?

答案1

得分: 1

以下是翻译好的代码部分:

  1. 这只是一个权宜之计未来将会改进但目前解决这个问题的方法是这样的mypy插件之外即在VS Code内置的检查器中)。
  2. from __future__ import annotations
  3. from typing import TYPE_CHECKING
  4. if TYPE_CHECKING:
  5. from django.db.models.manager import RelatedManager
  6. class RelModel(Model):
  7. belongs_to = models.ForeignKey(MyModel, related_name="things")
  8. class MyModel(Model):
  9. if TYPE_CHECKING:
  10. 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)

  1. from __future__ import annotations
  2. from typing import TYPE_CHECKING
  3. if TYPE_CHECKING:
  4. from django.db.models.manager import RelatedManager
  5. class RelModel(Model):
  6. belongs_to = models.ForeignKey(MyModel, related_name="things")
  7. class MyModel(Model):
  8. if TYPE_CHECKING:
  9. 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:

确定