Django says my model is undefined

So, I am developing a project using Django, and I am trying to create some links between some models, such as User and Country. When I try to synchronize my console outputs, "Country name is not defined." Check the code:

class User(models.Model): name = models.CharField(max_length=50,null=False) email = models.EmailField(max_length=50,null=False) password = models.CharField(max_length=10,null=False) country = models.ForeignKey(Country,null=False) #error here rol = models.ForeignKey(Rol,null=False) job = models.ManyToManyField(Job) #UserxJob skill = models.ManyToManyField(Skill) #UserxSkill plan = models.ManyToManyField(Plan) #UserxPlan image = models.ForeignKey(Image) description = models.TextField(max_length=300) website = models.URLField(max_length=100,null=True) def __unicode__(self): return self.name class Country(models.Model): name = models.CharField(max_length=50,null=False) def __unicode__(self): return self.name 

Could you help me with this?

+4
source share
2 answers

Move Country class definition above User in file

OR

In the User model, update the Country attribute to:

 country = models.ForeignKey('Country',null=False) 

Documentation about this can be found here.

+16
source

You need to move the country definition above the user definition.

What happens, the compiler (when compiled into .pyc-byte code) compiles the class definition for the user and sees a reference to an object of type Country. The compiler has not yet seen this definition and does not know what it is, so its error is not defined.

So, the basic rule of the thumb โ†’ Everything should be defined before calling or linking to it

+2
source

Source: https://habr.com/ru/post/1491475/


All Articles