Azd325
Azd325

Reputation: 6140

Difference between using name of model and model for ForeignKey

In the Django docs entry for ForeignKey, it says:

If you need to create a relationship on a model that has not yet been defined, you can use the name of the model, rather than the model object itself:

e.g. name

class Car(models.Model):
    manufacturer = models.ForeignKey('Manufacturer')

or object

class Car(models.Model):
    manufacturer = models.ForeignKey(Manufacturer)

What is the difference between these two variants?

Upvotes: 3

Views: 84

Answers (2)

Problematic
Problematic

Reputation: 17678

Your second example refers directly to the class itself, and requires that the class be defined or imported before you use it, while the first will use Django's model loading framework.

Usually, referring to the class directly is fine. In instances where it's not preferable or possible (if you are, for example, defining Manufacturer later in the same file, or if importing the class would cause issues with circular imports), the string syntax will let you set up the relationship sanely.

Upvotes: 3

Burhan Khalid
Burhan Khalid

Reputation: 174708

If in models.py you have this:

class Car(models.Model):
    name = models.CharField(max_length=200)
    manufacturer = models.ForeignKey(Manufacturer)

class Manufacturer(models.Model):
    name = models.CharField(max_length=200)

Since the class Manufacturer is defined after Car, when the interpreter reaches this line: models.ForeignKey(Manufacturer), it cannot find a name Manufacturer in the namespace, and it will result in an error.

To get around this, typically you change the order of definition:

class Manufacturer(models.Model):
    name = models.CharField(max_length=200)

class Car(models.Model):
    name = models.CharField(max_length=200)
    manufacturer = models.ForeignKey(Manufacturer)

Now, when the interpreter reaches the manufacturer foreign key definition, the class has already been defined (since its declared before the Car class). The other way to do this; if you don't want to shuffle the order in which the models are declared is to use a string which is the name of the model you want to refer to. Since its a string and not a name, Python will not raise an error.

Upvotes: 2

Related Questions