Django Primary Keys

May 14, 2010

If you have a Django model that has been generated from an existing database, you'll need to specify primary keys manually, by adding primary_key=True to the correct model field

id = models.IntegerField(primary_key=True, db_column='serial')

However, if the database auto populates the primary key, for example if you're using Postgres' primary key field type, then this will fail on save. It will complain that you've tried to put null into the serial column: null value in column "serial" violates not-null constraint.

The fix for this is to use AutoField rathern than IntegerField:

id = models.AutoField(primary_key=True, db_column='serial')