0

I have a non-primary key integer field in my Django model and I use Postgresql for database.

class TestModel(models.Model)
    pid = models.IntegerField(blank=True)
    some_field = models.CharField()

I want my pid field to have default values, that appear in database, I set the serial type for the pid field on the DB side

alter column pid type serial not null;

but when I create some record without without specifying value for pid, Django gives an error "null value in column "pid" violates not-null constraint", although it works fine when inserting data via SQL directly into database. I found this Django and PostgreSQL sequence for primary key autoincrement, but it's not working for me

CoffeeTableEspresso
  • 2,614
  • 1
  • 12
  • 30

2 Answers2

0

According to the documentation, you need to use AutoField. Like:

pid = models.AutoField(blank=true)

because what you change in database doesn't reflect to your Django immediately, better of changing your model and migrate your changes.

Alvi15
  • 335
  • 2
  • 10
  • I tried this, but it says "AutoFields must set primary_key=True". – dreamquester Nov 10 '20 at 09:36
  • https://stackoverflow.com/questions/41228034/django-non-primary-key-autofield well the other way is to do this. @dreamquester – Alvi15 Nov 10 '20 at 09:48
  • yeah, I am thinking of this too, I created a method like this, but thought I could do it without additional methods, just on DB side. Thank you. – dreamquester Nov 10 '20 at 09:51
0

You can generate the default values or use the AutoFiled.

https://docs.djangoproject.com/en/3.1/ref/models/fields/#default

After making changes to your models, always use makemigrations and migrate to reflect the changes into the db.

Saket B
  • 41
  • 1
  • 6
  • It seems that there is no way to avoid inserting null value into a field, when saving a model object and I really have to use signals or create some method to generate a default value. Thanks – dreamquester Nov 10 '20 at 09:39