Django ORM: Models with 2 table referencing each other
<p>I have 2 tables. User and Group. 1:Many relationship. Each user can only belong to a single group. </p>

<p>here's the model.py. </p>

<pre><code>class Group(models.Model):
    group_name = models.CharField(max_length=150, blank=True, null=True)
    group_description = models.TextField(blank=True, null=True)
    group_creator = models.ForeignKey(User, models.DO_NOTHING)

class User(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    ...
    group = models.ForeignKey(Group, models.DO_NOTHING)
</code></pre>

<p>The issue I have is that they are both referencing each other which is acceptable in MySQL and Oracle, but, I get an error when migrating:</p>

<blockquote>
  <p>group_creator = models.ForeignKey(User, models.DO_NOTHING)
  NameError: name 'User' is not defined</p>
</blockquote>

<p>Now when I reverse the order (so, User first than Group), I get</p>

<blockquote>
  <p>group = models.ForeignKey(Group, models.DO_NOTHING, blank=True, null=True)
  NameError: name 'Group' is not defined</p>
</blockquote>

<p>This is getting quite frustrating. I have a few work around (make it a many:many and keep creator on Group class), but before I start destroying my datamodel and move data move all the data around, I wonder if anyone has this issue before. How did you solve this? Do you really have to change your datamodel?</p>

<p>Add <code>related_name</code> to your <strong>ForeignKey</strong> fields:</p>

<pre><code>class Group(models.Model):
    group_name = models.CharField(max_length=150, blank=True, null=True)
    group_description = models.TextField(blank=True, null=True)
    group_creator = models.ForeignKey('User',related_name='myUser')

class User(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    group = models.ForeignKey('Group', related_name='MyGroup')
</code></pre>

python mysql django