I set default value as 0 in foreign key field in Django model. But it is raising IntigrityError (1048, "Column 'country_id' cannot be null")
Hi, I have code like:
name = models.CharField(max_length=255, blank=True)
reg_from = models.CharField(max_length=255, blank=True)
gender = models.CharField(max_length=1, choices=GENDER_CHOICES, blank=True, null=True)
country = models.ForeignKey(Country, blank=True, default=0)
For some reason, while saving TestModel, I can't provide country information. I would like to update that later.
It's raising an error because there isn't an object in your Country models that has a
PK = 0.
If you do not want to set your field to
null then simply create a Country object with
Country.objects.create(name='No Country', pk=0).
Although, setting the field to
null and having
default=0 might be a cleaner solution.
Try None instead of 0. 0 is an integer, it should not work anyway.
I made field null as quick and dirty solution.
Change your definition to:
country = models.ForeignKey(Country, blank=True, null=True, default=0)
null=True attribute will set NULL parameter on the
country column in the DB, without that you should set a value for this column.
default=0 is not necessary, because the default value will be null.