[Answered ]-Django models relation to two models before saving

1👍

The error is because you have a circular import. It’s not possible to for both modules to import from each other.

In this case, you don’t need to import the models into each app. Remove the imports, and use a string app_label.ModelName instead.

# app1.models.py
class FirstModel(models.Model):
    first_field = models.ManyToManyField('app2.SecondModel')

# app2.models.py
class SecondModel(models.Model):
    second_field = models.ForeignKey('app1.FirstModel')

1👍

there is a name conflict here .. you defined the FirstModel in your models.py and then defined FirstModel, from the code above, this could be the possible problem. Also, the import error generally mean, there is no FirstModel defined from where you are importing it.

However, a more generic way of doing FKs without import is generally

class FkModel(models.Model):
    relationship = models.ManyToManyField('appName.modelName')

where appName is the app from where you are trying to import the model from, and modelName is the model to which you are trying to create the relationship. This helps where you are trying to do something like this.

Lets say your app name is ‘app’ and you are trying to create a many to many relationship from 1st model to a 2nd model for which the class is declared after the 1st model e.g.

class Model1(models.Model):
    first_field = models.ManyToManyField('app.Model1')

class Model2(models.Model):
    name = models.CharField(maxlength=256)

that is just put your appname.modelName inside strings 🙂

also, you have a flaw in your ManyToManyField() declaration i.e. you don’t need to define blank in Many to Many. The way db’s work under the hood is, they create a 3rd database table just to store many to many relationships.

hope it helps

//mouse.

Leave a comment