使用Django 1.11和一个postgreSQL数据库(刚从sqlite切换过来,之前没有这个问题)
所以我有3个模型:
所以我要实现的逻辑是,如果
我找不到正确的选项来实现这一点:
如果没有
所以我有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
,则可以创建一个具有空或null字段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
。
在postgreSQL中,有没有一种让OneToOneField
可选为空的方法?
还有其他/更简单的实现这种逻辑的方法吗?
感谢您的帮助!