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

后端 未结 3 1283
一向
一向 2020-12-28 21:51

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

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


        
相关标签:
3条回答
  • 2020-12-28 22:23

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

    0 讨论(0)
  • 2020-12-28 22:25

    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.

    0 讨论(0)
  • 2020-12-28 22:31

    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).

    0 讨论(0)
提交回复
热议问题