Django:为什么在ForeignKey定义中在模型周围使用引号 [英] Django: Why are quotes around the model in a ForeignKey definition

查看:206
本文介绍了Django:为什么在ForeignKey定义中在模型周围使用引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道这两个外键定义之间的区别。

I want to know what the difference between these two foreignkey definitions are.

(1) MyFKField = models.ForeignKey('MyModel')
(2) MyFKField = models.ForeignKey(MyModel)

我了解(我认为...)(1) MyModel 需要在同一文件中定义,而另一个需要导入,但是我不确定原因/

I understand (I think...) that (1) MyModel needs to be defined in that same file and the other needs to be imported, but I'm unsure of the reason/benifits of doing it either way.

我浏览了Django文档,但找不到任何东西,我也不知道这是问的正确地方,所以

I had a look through the Django docs but couldnt find anything, and Im also not sure if this is the right place to ask, so apologies if not.

干杯

推荐答案

Django文档指出您要在(1)中使用字符串:

Django docs states that you would use a string to (1):


  • 您想要递归关系(例如- model.ForeignKey('self')

  • 用于引用可能尚未定义的模型(用于循环
  • 在另一个应用程序中引用模型的快捷方式(例如- model.ForeignKey('app.mymodel')

  • You want a recursive relationship (eg - model.ForeignKey('self'))
  • For referring to a model that is possibly not defined yet (for cyclic relationships).
  • A shortcut to refer to a model in another application (eg - model.ForeignKey('app.mymodel'))

但是通常,直接指定模型类很容易知道它来自(2)的位置。

But in general, specifying the model class directly is clear where it's coming from (2).

这篇关于Django:为什么在ForeignKey定义中在模型周围使用引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆