Django models foreign key not recognizing 'QueryString' BaseObject
I am currently working on a Django 1.5.2 project within a Docker instance that speaks with a mysql database in a separate Docker instance. I am trying to create a Many to Many relationship between two tables by creating a middle table that contains two foreign keys that point to the two tables that need connecting. The problem arises when I run
python manage.py syncdb and it spits out the following error to the terminal:
NameError: name 'QueryString' is not defined.
QueryString is clearly defined in my models.
Here are my Models…
class Tag(models.Model): name = models.CharField(max_length=100) class QueryStringTab(models.Model): tag = models.ForeignKey(Tag, related_name='querystringtab') querystring = models.ForeignKey(QueryString, related_name='querystringtab') class QueryString(BaseObject): """ Query string holds an SQL statement and query properties for execution """ server_id = models.IntegerField() schema = models.CharField(max_length=255, blank=True) query = models.CharField(max_length=60000) variables = models.TextField(blank=True) created_by = models.ForeignKey(User, related_name='queries_created') updated_by = models.ForeignKey(User, related_name='queries_last_edited') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField() touched_by = models.CharField(max_length=1000) config = models.TextField(blank=True) runs_started = models.IntegerField(default=0) runs_completed = models.IntegerField(default=0) runs_completed_duration = models.IntegerField(default=0) # total number of seconds spent running this query to completion formats = "pretty_html html json prettyjson csv excel tableau".split()
1) It is recognizing the
Tag model just fine.
2) Could it have something to do with the fact that
QueryString is a
3) It is successfully creating the
Tag table in the mysql database
Can anyone find anything obvious that I am doing wrong?
One Solution collect form web for “Django models foreign key not recognizing 'QueryString' BaseObject”
The declaration of QueryStringTab is before the one for QueryStringTab; so when Python evaluates the first, it has not yet seen any definition for the second and therefore reports a NameError.
Django allows you to use a string target than a class object in cases like this:
querystring = models.ForeignKey('QueryString', related_name='querystringtab')
Or, you could simply move the definition of QueryStringTab to the end.