简体   繁体   English

为什么要设置外键django的默认值

[英]Why should I set default value of foreign key, django

For example, we have this code: 例如,我们有以下代码:

class Foo(models.Model):
    a = models.CharField(max_length=10)


class Bar(models.Model):
    b = models.CharField(max_length=10)
    a = models.ForeignKey(Foo)

And when I run makemigrations, i see that I need set default of a(Bar) Can anyone explain me, why should I do it? 当我运行makemigrations时,我看到我需要将a设置为默认值(Bar)谁能解释我,我为什么要这样做?

Thanks! 谢谢!

It seems that you already have some data in your database (or you have made a migration before adding the ForeignKey field). 看来您的数据库中已经有一些数据(或者在添加ForeignKey字段之前进行了迁移)。 In order for the migration to work you will need to "tell" Django what data should be in the a column of the Bar table for rows that already exist. 为了使迁移正常进行,您将需要“告诉” Django,对于已存在的行, Bara列中应包含哪些数据。

Either delete your whole database/earlier migrations, or provide a default value of your choice: 删除整个数据库/较早的迁移,或者提供您选择的默认值:

a = models.ForeignKey(Foo, default=None) # or any other default value

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM