Reputation: 4743
I've a database design corresponding to the following pseudo-code:
class AModel(models.Model):
c_model_instances = models.OneToOne(CModel, ...) # "is a" relationship
class BModel(models.Model):
a_model_instances = models.ManyToMany(AModel, ...) # "contains" relationship
class CModel(models.Model):
b_model_instances = models.ManyToMany(BModel, ...) # "contains" relationship
Belief it or not... this design makes total sense from a business perspective :) However of course I get an error NameError: name 'CModel' is not defined
when I try to migrate the database. How can I resolve or fix (via different design) the issue?
Upvotes: 1
Views: 216
Reputation: 477854
You can use string literals, instead of an identifier that points to a model, as described in the documentation:
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.
For example:
class AModel(models.Model):
c_model_instances = models.OneToOne('django_app_name.CModel', …) # "is a" relationship
class BModel(models.Model):
a_model_instances = models.ManyToMany(AModel, …) # "contains" relationship
class CModel(models.Model):
b_model_instances = models.ManyToMany(BModel, …) # "contains" relationship
Django will automatically replace the string literals with references to the models.
Upvotes: 1