【发布时间】:2018-05-27 23:48:30
【问题描述】:
使用 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_parent 是True,则可以使用after_homework 的空字段或空字段创建VideoGamePurchase 实例。但是,如果 Person.is_parent 是 False,我希望该字段成为唯一 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=True或blank=True。
有没有办法让 OneToOneField 使用 postgreSQL 为空?
还有其他/更简单的方法来实现这种逻辑吗?
感谢您的帮助!
【问题讨论】:
标签: python django postgresql one-to-one