[Django]-Difference between using name of model and model for ForeignKey

3👍

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.

2👍

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.

Leave a comment