开发者

Django: Why are quotes around the model in a ForeignKey definition

I want to know what the difference be开发者_Go百科tween these two foreignkey definitions are.

(1) MyFKField = models.ForeignKey('MyModel')
(2) MyFKField = models.ForeignKey(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.

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.

Cheers


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

  • 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'))

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


Without quotes, it's a reference to a model either defined within the file or imported via import. With quotes, Django is made responsible for finding the model among all the models in all installed apps.


If the definition of class MyModel is under the definition of class MyFKField (in the code) then you should write it between quotes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜