【发布时间】:2016-08-04 13:32:38
【问题描述】:
我有两个模型,Article 和 ArticlePost。 ArticlePost 将 Article 引用为外键,并且在 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)
我已经运行了 python manage makemigrations,它给出了以下内容:
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')),
],
),
]
但是,当我运行 python manage migrate 时,我得到:
django.db.utils.ProgrammingError: there is no unique constraint matching given keys for referenced table "article"
奇怪的是我在app1 中有另一个模型,它也引用了具有完美工作的外键的文章。但是在这种情况下,Django 似乎不知道哪个字段是Article 的主键。唯一的区别是ArticlePost 与Article 在不同的应用程序中。我正在运行 Django 1.10。有谁知道是什么原因造成的以及如何解决?
或者,如果这只是一个关键问题,也许解决方案是删除文章上的 primary_key 并改用 Django 默认的 id。在这种情况下,如何在保持其他模型对 app1 内文章的外键引用的同时最好地做到这一点?
【问题讨论】:
-
这不能回答您的问题,但您可以在模型字段中删除
null=False。默认情况下,null=False。如果您将其设置为True,则只需添加null值。
标签: python django django-models django-postgresql