Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

django

I want to know what the difference between 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

like image 576
neolaser Avatar asked Jan 16 '11 23:01

neolaser


People also ask

What does ForeignKey mean in Django?

What is ForeignKey in Django? ForeignKey is a Field (which represents a column in a database table), and it's used to create many-to-one relationships within tables. It's a standard practice in relational databases to connect data using ForeignKeys.

What is the difference between ForeignKey and OneToOneField?

The only difference between these two is that ForeignKey field consists of on_delete option along with a model's class because it's used for many-to-one relationships while on the other hand, the OneToOneField, only carries out a one-to-one relationship and requires only the model's class.

What is Db_column?

db_column. The name of the database column to use for this field.


1 Answers

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

like image 124
Jeff Avatar answered Oct 27 '22 20:10

Jeff