Django Tutorials: Creating Relationships to Models Not yet Defined

By: Dusty Arlia
Published on Friday, March 21, 2014, 11:10 AM
Last Updated on Monday, July 06, 2015 at 10:02 PM
Total Updates: 2

To create a relationship on a Django model that has not yet been defined, use a string of the name of the model instead of the model object variable name. Here is an example:

from django.db import models

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

class Manufacturer(models.Model):
    # ...
    pass

The name of the ForeignKey above is manufacturer (left of the assignment operator). It is recommended that you use the name of the model in lowercase as the name of your ForeignKey (though not required).

Comments:

Ad:

Ad: