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

0

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I tried this, but it says "AutoFields must set primary_key=True".
stackoverflow.com/questions/41228034/… well the other way is to do this. @dreamquester
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.
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.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.