migrate fails when giving default=0 on a ForeignKey

Why does migrate on this fail in-spite of mentioning db_constraint=False ?

cust_tbl = models.ForeignKey(Customer, on_delete=models.CASCADE, default=0, db_constraint=False)

The issue you’re experiencing might be related to the fact that Django doesn’t allow setting a default value of 0 for a ForeignKey field. When specifying default=0 for a ForeignKey, Django will try to find an object with a primary key of 0 in the related model, and if it doesn’t exist, it will raise an integrity error during the migration.

Also, The db_constraint parameter set to False only affects the database level constraints. It prevents the creation of a foreign key constraint at the database level, but it doesn’t bypass Django’s validation during migrations. Check here Model field reference | Django documentation | Django.

If you want to set ForeignKey to be nullable you can use null=True.

1 Like