Model not defined when using foreign key to second model

Question:

I’m trying to create several relationships between some models such as User and Country. When I try to syncdb, my console outputs "Name Country is not defined".

Here is 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

    
class Country(models.Model):
    name = models.CharField(max_length=50, null=False)

Could you please help me out with this one?

Asked By: user1659653

||

Answers:

Either move the class definition of Country on above User in the file

OR

In the User model, update the attribute country to:

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

Documentation on this can be found here

Answered By: karthikr

You need to move the definition of Country above the definition of User.

What is happening is the compiler (when compiling to .pyc byte code) is compiling the Class definition for User and sees a reference to a Country type object. The compiler has not seen this definition yet and does not know what it is, hence the error of it being not defined.

So the basic rule of thumb-> Everything has to be defined before you call or reference it

Answered By: Paul Renton
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.