简体   繁体   English

Django 1.7中的外键完整性错误

[英]Foreign Key Integrity error in Django 1.7

I have a project where a user can review a service. 我有一个用户可以查看服务的项目。 Whenever I try to write a review with the same user twice, I get an Integrity error: 每当我尝试用同一用户两次撰写评论时,都会收到“完整性”错误:

duplicate key value violates unique constraint "reviews_review_user_id_key" DETAIL: Key (user_id)=(7) already exists.

I'm not too sure why I am getting this error. 我不太确定为什么会收到此错误。 Is it because there should be a many-to-many relation between users and reviews? 是因为用户和评论之间应该存在多对多关系?

The review model looks like this: 审查模型如下所示:

class Review(models.Model):
    user = models.ForeignKey(User)
    service = models.ForeignKey('services.Service')
    rating_value = models.IntegerField(default = 0)
    review_text = models.CharField(max_length = 500, default= "null")
    pub_date = models.DateTimeField(default=timezone.now,blank=True)
    def __str__(self):              # __unicode__ on Python 2
        return self.service_name

It appears that you have removed the unique constraint in the models.py, but the unique constraint still exists on the database table. 看来您已经删除了models.py中的唯一约束,但是唯一约束仍然存在于数据库表中。 This has happened to me before and I was able to remove the constraint from the table through ./manage.py dbshell and everything worked as expected. 这以前发生在我身上,我可以通过./manage.py dbshel​​l从表中删除约束,一切都按预期工作。

Not sure which db you're using, but for postgres it would be: ALTER TABLE your_table DROP CONSTRAINT reviews_review_user_id_key; 不知道您使用的是哪个数据库,但是对于postgres来说应该是: ALTER TABLE your_table DROP CONSTRAINT reviews_review_user_id_key;

Give that a shot, hope it helps. 试一试,希望对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM