'django.db.utils.IntegrityError: null value in column "id" violates not-null constraint
I want to save data from the Django model to PostgreSQL database with:
mymodel.objects.create(title='test')
this model only has title and id but it raises this error:
django.db.utils.IntegrityError: null value in column "id" violates not-null constraint
how can I fix it? why id is not set automatically as always?
Solution 1:[1]
You should allow Django to create the id as the primary key instead of explicitly putting it in your model. You could call it something else like mymodel_id if you need it as a separate field.
Example:
class Book(models.Model):
title = models.CharField(null=False, blank=False)
def __str__(self):
return str(self.id)
After that run:
python manage.py makemigrations
python manage.py migrate
If you need to integrate Django with an existing database you can try this: Integrating Django with an existing database
Solution 2:[2]
If you somehow had your ID field altered on the database level and you want to make it an autoincrementing sequence again do this
In the below example check what mymodel's table will be in Postgres in the example below its called mytable
// Pick a starting value for the serial, greater than any existing value in the table
SELECT MAX(id)+1 FROM mytable
// Create a sequence for the serial (tablename_columnname_seq is a good name)
CREATE SEQUENCE mytable_id_seq MINVALUE 3 (assuming you want to start at 3)
// Alter the default of the column to use the sequence
ALTER TABLE test ALTER id SET DEFAULT nextval('mytable_id_seq')
// Alter the sequence to be owned by the table/column;
ALTER SEQUENCE mytable_id_seq OWNED BY mytable.id
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 |