[Fixed]-Django: Why are quotes around the model in a ForeignKey definition

18👍

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

👤Jeff

13👍

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👍

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

Leave a comment