当前位置: 动力学知识库 > 问答 > 编程问答 >

python - default value 0 in foreign key field raising error

问题描述:

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:

class TestModel(models):

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.

Krish

网友答案:

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 pk=0 like: 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)

The null=True attribute will set NULL parameter on the country column in the DB, without that you should set a value for this column.

Also default=0 is not necessary, because the default value will be null.

分享给朋友:
您可能感兴趣的文章:
随机阅读: