3

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?

Kane Blueriver
  • 4,170
  • 4
  • 29
  • 48

1 Answers1

5

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.

v1k45
  • 8,070
  • 2
  • 30
  • 38
  • 1
    After migrating, this works. But the doc says this is the default behavior, does this means I don't need to define `id` field manually? – Kane Blueriver Apr 05 '16 at 07:46
  • Another question, If I want key `id` starts from 300000, what should I do? – Kane Blueriver Apr 05 '16 at 07:46
  • Yes, django adds `id` AutoField by default. You don't need to add manually if you wish to name it as `id`. – v1k45 Apr 05 '16 at 07:47
  • You can change that at DB level. See: http://stackoverflow.com/questions/117800/how-to-get-django-autofields-to-start-at-a-higher-number – v1k45 Apr 05 '16 at 07:48
  • Emm, maybe better to add it in migration files, so every developer in my team will gets the convenient. Really helps, thanks! – Kane Blueriver Apr 05 '16 at 07:50