django inspectdb 'unique_together' refers to the non-existent field
<p>I have a legacy database that I wish to use as a second database in my django project.  I added the database to my settings file, and ran:</p>

<pre><code>python manage.py inspectdb --database=images
</code></pre>

<p>The script finished in less than a second, and the results were astounding.  It understood all my tables - or so I thought at first.  When I tried to run:</p>

<pre><code>python manage.py migrate --database=images
</code></pre>

<p>I got errors like this:</p>

<pre><code>'unique_together' refers to the non-existent field 'commentaryId'.
</code></pre>

<p>All of the tables that raised errors were many-to-many linking tables containing two id fields that together formed the primary key (and thus had to be 'unique together').</p>

<p>Here is one of the models, created by inspectdb, that raised this error:</p>

<pre><code>class Pagescanannotationscommentaries(models.Model):
    pagescanannotationid = models.IntegerField(db_column='pageScanAnnotationId')  # Field name made lowercase.
    commentaryid = models.IntegerField(db_column='commentaryId')  # Field name made lowercase.

    class Meta:
        managed = False
        db_table = 'PageScanAnnotationsCommentaries'
        unique_together = (('pageScanAnnotationId', 'commentaryId'),)
</code></pre>

<p>I found several questions like mine in stackoverflow, but the suggestions did not help me, or were obviously not relevant.  But I did find a post in google groups that gave me the tip that fixed it: <a href="https://groups.google.com/forum/#!topic/django-users/_phTiifN3K0" rel="nofollow">https://groups.google.com/forum/#!topic/django-users/_phTiifN3K0</a></p>

<p>But even then, my problem was a bit different, I found, and I explain in the answer below.</p>

<p>django's inspectdb took my legacy field names as the field names for unique_together.  I changed this so it used the properties in the model, and that solved the problem.  I also added the _ before the id, as stated in the google groups post listed above.  But I am not sure if that underscore was relevant.  Right now, I don't want to mess with my set up, so I leave the test with the underscores (or rather without underscores) to someone else.  :-)  If I have time to test that, I will post what I find here.</p>

<p>Here is my working model code:</p>

<pre><code>class Pagescanannotationscommentaries(models.Model):
    pagescanannotation_id = models.IntegerField(db_column='pageScanAnnotationId')  # Field name made lowercase.
    commentary_id = models.IntegerField(db_column='commentaryId')  # Field name made lowercase.

    class Meta:
        managed = False
        db_table = 'PageScanAnnotationsCommentaries'
        unique_together = (('pagescanannotation_id', 'commentary_id'),)
</code></pre>

<p>This change made the error message disappear.</p>

python django inspectdb