[英]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: 解决此问题的方法:
ALTER TABLE city ADD COLUMN city_id SERIAL PRIMARY KEY
After that, my problem is solved. 之后,我的问题解决了。 Hope this helps other people facing a similar problem!
希望这可以帮助其他面临类似问题的人!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.