-1

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.

Meera K
  • 11
  • 5

1 Answers1

0

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

Maxim Danilov
  • 2,472
  • 1
  • 3
  • 8
  • Thank you Maxim! List is the table of all customer details. In the form, one field is State being a drop down listing records from the table 'State'. Yes, db_column="State" does have only unique keys. For each customer row detail there can be only 1 State linked. So I guess the foreign key should be in List. The state field currently accept null value as not all customer addresses are stored in the List, only certain customers. So the List.State column should be allowing null value though it is linked with the State table. – Meera K Jul 07 '22 at 12:28
  • Also, from the error I think it says that there should be null value even in State table. is it not? The solution code you had given, where should I insert? in models? or views? Kindly guide. - thank you! – Meera K Jul 07 '22 at 12:28
  • you should put it in Model List – Maxim Danilov Jul 07 '22 at 12:33