I'm working with a new Django project which need to load data from a legacy db, but saving new model object always fails with IntegrityError: null value in column "id" violates not-null constraint after I loaded data from the legacy db.
Primary key in legacy db is in range from 10000 to 200000, the new db is Postgres 9.5 and never manual set SQL schema on it.
My model could be simple like:
class MyModel(Model):
id = IntegerField(primary_key=True)
This will fails when I run MyModel().save() or MyModel.create(). It's OK to run MyModel(id=233).save() like I used at loading data.
I guess it's because it does not know where to start to auto generate primary key from. How to fix this?
To add an auto-increment field in django, you are supposed to use AutoField
You should define your id field like this:
id = models.AutoField(primary_key=True)
If you want to name it as id, you are not required to define the field, django does that for you.
A model without explicit id field will still have a AutoField id as a primary key.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With