Home > Software engineering >  column contains null values
column contains null values

Time:05-24

I added Person as a foreign key to the CareerHistory table.

    person = models.ForeignKey(
    Person, on_delete=models.PROTECT, default=None, related_name='careerist')

I set default=None thinking this would avoid that error when running migrations about making a new field on an existing table without a default value. However, instead I got

django.db.utils.IntegrityError: column "person_id" contains null values

Now, there are only 114 Persons in that table, and all of them have ids, so I find this error very confusing. I looked at this answer: SQL Django Null Constraint Error - cannot resolve?

and decided to try:

            person = models.ForeignKey(
    Person, on_delete=models.PROTECT, default='', related_name='careerist')

However, this still came back with the same error. Then I went to:

            person = models.ForeignKey(
    Person, on_delete=models.PROTECT, default='', null=True, related_name='careerist')

But I still get the same error. I don't understand what is happening here. Can someone please explain, and show me how to fix this? I don't want to just fix it, I want to understand what is happening here. Maybe I need to edit my migrations file(s)? Thanks.

CodePudding user response:

The problem is that your adding the field, but without allowing null. By adding null=True you should resolve the issue during the migration.

person = models.ForeignKey(
    Person, 
    on_delete=models.PROTECT, 
    null=True,
    default=None, 
    related_name='careerist'
)

there are 114 Persons in that table, and all of them have ids, so I find this error very confusing

So when you add this column, the database doesn't know which career belongs to which person. So you have to implement a database migration to connect these two.

After the datamigration it's possible to remove the null=True, default=None.

  • Related