【问题标题】:Django OneToOneField with possible blank field带有可能空白字段的 Django OneToOneField
【发布时间】: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_parentTrue,则可以使用after_homework 的空字段或空字段创建VideoGamePurchase 实例。但是,如果 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 为空?

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

感谢您的帮助!

【问题讨论】:

    标签: python django postgresql one-to-one


    【解决方案1】:

    如果您希望after_homework 字段是可选的,那么您应该使用null=Trueblank=True

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

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

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

    【讨论】:

      猜你喜欢
      • 2012-12-13
      • 2019-06-19
      • 1970-01-01
      • 1970-01-01
      • 2014-04-06
      • 2013-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多