Search code examples
djangomodelforeign-keysintegrationmigrate

Django django.db.utils.IntegrityError


Model:

class List(models.Model):
    Lid = models.AutoField(primary_key=True)
    Name = models.CharField(max_length=100)
    addr1 = models.CharField(max_length=100)
    addr2 = models.CharField(max_length=100) 
    City = models.CharField(max_length=40) 
    State = models.ForeignKey(State,blank=True, on_delete=models.DO_NOTHING, default=None,to_field="state",db_column="State") #,to_field="state",db_column="State"

Below is the error appears when tried to migrate,

IntegrityError( django.db.utils.IntegrityError: The row in table 'list' with primary key '1' has an invalid foreign key: list.State contains a value '' that does not have a corresponding value in State.state.

How to fix this issue? I did add those 'blank=True' and on_delete=models.DO_NOTHING after searching for a solution in google, still no luck.


Solution

  • If you want have row from List and 1 row from State. It can be o2o-key (don't matter which model), or you can use Foreign-key in List. But: DB-Table State should have in your db_column="State" only unique keys.

    If you want to have every row from List and some rows from State. Foreign key should be in State model, not in List.

    After that: On migration you should convert column list.state to value_type like in state.state.

    For example you have type(list.state) = string and type(State.state) = integer. It can works without it, i know, but it is better to check it on migration. if you have in list.state default=None, also you can convert every_list_row.state = '' to every_list_row.state = None, to avoid problem in future, on export etc.

    If you receive ForeignObjectException - object not exists on list_row.state: You can create something like that:

    @property    
    def get_state(self):
            return hasattr(list_row, 'state') and list_row.state or ''
    

    and after that: list_row.get_state