Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django ORM cannot auto set primary key for model after loading data from legacy db

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?

like image 934
Kane Blueriver Avatar asked May 16 '26 23:05

Kane Blueriver


1 Answers

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.

like image 151
v1k45 Avatar answered May 18 '26 11:05

v1k45



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!