Django OneToOneField可能包含空白字段

时间:2017-12-14 00:11:55

标签: python django postgresql one-to-one

使用Django 1.11和 postgreSQL数据库(刚从sqlite切换,之前没有遇到此问题)

所以我有3个型号:

models.py

class Person(models.Model):
    is_parent = models.BooleanField()

class VideoGamePurchase(models.Model):
    bought_by = models.ForeignKey(Person)
    after_homework = models.OneToOneField(HomeWork, OPTIONS???)

class HomeWork(models.Model):
    done_by = models.ForeignKey(Person)
    content = models.CharField(blablaba)

因此,我尝试实现的逻辑是,如果Person.is_parentTrue,则可以使用VideoGamePurchase的空字段或空字段创建after_homework实例。但是,如果Person.is_parentFalse,我希望此字段成为唯一HomeWork对象的主键。

我无法找到实现这一目标的正确选择:

如果我没有primary_key=True那么makemigrations就会失败:

You are trying to add a non-nullable field 'id' to video_game_purchase without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
 1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
 2) Quit, and let me add a default in models.py

所以我想我有primary_key=True。但似乎我无法null=Trueblank=True

有没有办法让OneToOneField可选地为postgreSQL?

是否有其他/更简单的方法来实现这种逻辑?

感谢您的帮助!

1 个答案:

答案 0 :(得分:5)

如果您希望after_homework字段是可选字段,则应使用null=Trueblank=True

class VideoGamePurchase(models.Model):
    bought_by = models.ForeignKey(Person)
    after_homework = models.OneToOneField(HomeWork, null=True, blank=True)

您不希望primary_key=True成为after_homework,这会使after_homework成为VideoGamePurchase模型的主键字段,如果该字段是可选的。

您的迁移似乎搞砸了,因为之前primary_key=True字段有after_homework。最简单的解决方法是从新数据库开始,删除该应用的迁移,然后重新运行makemigrationsmigrate。这次,迁移将自动为id模型创建主键字段VideoGamePurchase