简体   繁体   中英

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?

Thanks!

It seems that you already have some data in your database (or you have made a migration before adding the ForeignKey field). 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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