I have two models, Article
and ArticlePost
. ArticlePost
references Article
as a foreign key and is in a separate application to Article
:
====app1/models.py:======
class Article(models.Model):
name = models.CharField(max_length=200, primary_key=True)
====app2/models.py======
class ArticlePost(models.Model):
article = models.ForeignKey(Article, null=False, db_index=True)
created_at = models.DateTimeField(auto_now_add=True)
comment = models.TextField(blank=True)
I have run python manage makemigrations which gives the following:
operations = [
migrations.CreateModel(
name='ArticlePost',
fields=[
('id', models.AutoField(auto_created=True, verbose_name='ID', serialize=False, primary_key=True)),
('created_at', models.DateTimeField(auto_now_add=True)),
('comment', models.TextField(blank=True)),
('article', models.ForeignKey(to='app2.Article')),
],
),
]
However when I run python manage migrate I get:
django.db.utils.ProgrammingError: there is no unique constraint matching given keys for referenced table "article"
What is strange is that I have another model in app1
which also references article with a foreign key which works perfectly. However in this case it would appear that Django does not know which field is the primary key for Article
. The only difference is that ArticlePost
is in a different application from Article
. I am running Django 1.10. Does anyone have any idea what is causing this and how it might be fixed?
Alternatively if it is just a key issue maybe a solution is to remove the primary_key
on Article and use the Django default id
instead. In this case, how is best to do this while maintaining the Foreign Key references from other models to Article within app1?