【问题标题】:Postgresql + Django : Not Null Fields Empty ValuePostgresql + Django:非空字段空值
【发布时间】:2018-10-14 15:49:02
【问题描述】:

我知道标题没有任何意义,但我只想知道如何在 Django 制作的 CharField 中插入空字符串或 ''?据我所知,默认情况下,Django 中的字段不可为空。检查 PGAdmin 中的数据,我可以看到大多数 CharFields 都有 '' 作为值。我想知道这怎么可能?如果我运行

  cur_p.execute("""
                INSERT INTO "table"name" (address, school_address, sports ) VALUES ('', '', '')

我会得到psycopg2.IntegrityError: null value in column "created" violates not-null constraint

我还注意到某些字段中有blank=True。如果你有一个不可为空的字段然后你声明blank=True,这不矛盾吗?

【问题讨论】:

  • 请给出你的模型的 CharField 代码。
  • address = models.CharField(max_length=250) school_adress = models.CharField(max_length=250) sports = models.CharField(max_length=50)
  • @tangoward 将null=True 添加到您希望能够设置为空的字段中,如果您有两个可能的值有什么关系?这是你想要的结果。
  • @tangoward 如果您真的想具体解释 blank=Truenull=True 的作用,请转到此答案:stackoverflow.com/a/8609425/7707749

标签: django postgresql


【解决方案1】:

查看documentation,您可以在字段定义中使用null=True 以允许postgres 为该列存储空值。

【讨论】:

  • 是的,这就是我的想法,但这些字段是 CharField。文档说avoid using null on string-based fields such as CharField and TextField. If a string-based field has null=True, that means it has two possible values for “no data”: NULL, and the empty string.
  • 我认为这是对我第二个关于拥有blank=True simpleisbetterthancomplex.com/tips/2016/07/25/… 的问题的最佳解释我仍然不知道如何在null=False CharField 中插入一个空字符串
猜你喜欢
  • 2018-07-04
  • 2015-02-21
  • 2012-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-04
  • 2015-08-09
  • 2017-04-04
相关资源
最近更新 更多