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.
精彩评论