【问题标题】:Django with Postgres: How To Allow Null as Default in Django Model带有 Postgres 的 Django:如何在 Django 模型中允许 Null 作为默认值
【发布时间】:2014-06-13 10:13:40
【问题描述】:

我正在使用带有 Postgres 的 Django,并尝试将数据从 csv 加载到表中。但是,由于一个字段是几何字段,所以我在加载表格时必须将其留空(否则\copy from会失败)。

这是我的模型:

name = models.CharField(max_length=200)
lat = models.DecimalField(max_digits=6, decimal_places=4, default=Decimal('0.0000'))
lon = models.DecimalField(max_digits=7,decimal_places=4, default=Decimal('0.0000'))
geom = models.PointField(srid=4326, blank=True, null=True, default=None)

迁移后,我像这样运行 psql:

mydb=>\copy target(name,lat,lon) from 'file.csv' DELIMITER ',' CSV HEADER ;

我得到这样的错误:

ERROR:  null value in column "geom" violates not-null constraint
DETAIL:  Failing row contains (name1, 30.4704, -97.8038, null).
CONTEXT:  COPY target, line 2: "name1, 30.4704, -97.8038"

这是 csv 文件的一部分:

name,lat,lon
name1,30.4704,-97.8038
name2,30.3883,-97.7386

这里是 \d+ 目标:

mydb=> \d+ target
                            Table "public.target"
   Column   |          Type          | Modifiers | Storage  | Stats target | Description 
------------+------------------------+-----------+----------+--------------+-------------
 name       | character varying(200) | not null  | extended |              | 
 lat        | numeric(6,4)           | not null  | main     |              | 
 lon        | numeric(7,4)           | not null  | main     |              | 
 geom       | geometry(Point,4326)   |           | main     |              | 
Indexes:
    "target_pkey" PRIMARY KEY, btree (name)
    "target_geom_id" gist (geom)

所以我猜在将 csv 加载到表时 geom 设置为 null ?我该如何解决?我想将归档geom的默认设置为null,以便我可以使用其他查询对其进行更新。

非常感谢!!

【问题讨论】:

  • 看起来我的表中可能需要这样的东西`CONSTRAINT enforce_geotype_geom CHECK (geometrytype(geom) = 'POINT'::text OR geom IS NULL)` 那么我该如何将它添加到我的表中通过姜戈?谢谢!
  • PostGIS 2.x 中看起来像 geometry(Point,4326) 的 typmods 不需要约束。当没有这样的约束时,为什么会出现错误““geom”列中的空值违反非空约束”?这是不可重现的。

标签: django postgresql postgis


【解决方案1】:

几个不同的选项,描述here

您可以:

1) 使用占位符 (0,0),然后您可以覆盖它。

或:

2) 设置spacial_index=False

【讨论】:

  • 谢谢,但在尝试spacial_index=False 后仍然无法正常工作。占位符的问题是,如果我知道如何在 csv 中呈现 (0,0) 以便 psql 中的\copy 可以工作,那么我不需要经历所有的麻烦.. 那么到底是什么我应该为 geom 字段输入 csv 吗?我试过ST_GeomFromText(Point(0 0), 4326),但失败了。
猜你喜欢
  • 2015-09-12
  • 2017-11-10
  • 2011-06-04
  • 1970-01-01
  • 2014-10-11
  • 1970-01-01
  • 2022-06-17
  • 2018-10-22
  • 2015-09-12
相关资源
最近更新 更多