简体   繁体   English

“ city_id”列中的空值违反了非空约束

[英]null value in column “city_id” violates not-null constraint

This error happens when I tried to use Django admin to add a new entry in the database. 当我尝试使用Django admin在数据库中添加新条目时,会发生此错误。 This error shows even I tried to add a new state. 该错误表明,即使我尝试添加新状态。 What's wrong with my model? 我的模型怎么了?

class City(models.Model):
    city_id = models.AutoField(primary_key=True)
    city = models.CharField(max_length=100, blank=True, null=True)
    state = models.ForeignKey('State', models.DO_NOTHING, blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'city'

    def __str__(self):
        return self.city

class State(models.Model):
    state_id = models.AutoField(primary_key=True)
    state = models.CharField(max_length = 10, blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'state'

    def __str__(self):
        return self.state

Just found out the problem: It's a problem with my PostgreSQL database. 刚发现问题:这是我的PostgreSQL数据库的问题。 This error shows even when I run INSERT in the database. 即使在数据库中运行INSERT ,也会显示此错误。 So the problem is because my PRIMARY KEY is not a SERIAL value, rather, it's an INTEGER , thus it cannot auto increment when I insert a new value. 所以问题是因为我的PRIMARY KEY不是SERIAL值,而是一个INTEGER ,因此当我插入新值时它不能自动递增。

To solve this problem: 解决此问题的方法:

  1. Delete the old integer id as well as all the foreign key constraint on it. 删除旧的整数id及其上的所有外键约束。
  2. ALTER TABLE city ADD COLUMN city_id SERIAL PRIMARY KEY
  3. Reconnect tables with new foreign keys 用新的外键重新连接表

After that, my problem is solved. 之后,我的问题解决了。 Hope this helps other people facing a similar problem! 希望这可以帮助其他面临类似问题的人!

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

相关问题 IntegrityError:“city_id”列中的空值违反非空约束 - IntegrityError: null value in column “city_id ” violates not-null constraint “ job_id”列中的空值违反了非空约束 - null value in column “job_id” violates not-null constraint Django:关系的“id”列中的 null 值违反非空约束 - Django : null value in column "id" of relation violates not-null constraint “ user_id”列中的空值违反了非空约束 - null value in column “user_id” violates not-null constraint Flask SQLAlchemy null “id”列中的值违反非空约束 - Flask SQLAlchemy null value in column "id" violates not-null constraint Django-“ imageLink”列中的空值违反了非空约束 - Django - Null value in column “imageLink” violates not-null constraint Django - 列中的空值违反了 Django 管理中的非空约束 - Django - null value in column violates not-null constraint in Django Admin 保存ModelForm时,列中的null值违反非空约束 - null value in column violates not-null constraint while saving ModelForm Django:“is_admin”列中的 null 值违反了非空约束 - Django: null value in column "is_admin" violates not-null constraint 关系“blog_comment”的“comment_id”列中的 null 值违反了非空约束 - null value in column “comment_id” of relation “blog_comment” violates not-null constraint
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM