【发布时间】:2021-10-01 02:54:56
【问题描述】:
我正在尝试将 .csv 文件导入到我的 Django db.sqlite3 中,我完全按照 Youtube 视频中的说明进行操作。但是,我的 .csv 文件中有几行具有相同的纬度和经度值,并且 sqlite3 无法导入某些行,因为表中已经出现了纬度和经度。
sqlite> .import venues.csv myapi_venue
venues.csv:17: INSERT failed: UNIQUE constraint failed: myapi_venue.name
venues.csv:44: INSERT failed: UNIQUE constraint failed: myapi_venue.name
venues.csv:49: INSERT failed: UNIQUE constraint failed: myapi_venue.name
venues.csv:60: INSERT failed: UNIQUE constraint failed: myapi_venue.name
venues.csv:66: INSERT failed: UNIQUE constraint failed: myapi_venue.name
venues.csv:73: INSERT failed: UNIQUE constraint failed: myapi_venue.name
venues.csv:80: INSERT failed: UNIQUE constraint failed: myapi_venue.name
我试图强制模型具有唯一性为 False,但它没有帮助。
class venue(models.Model):
name = models.CharField(_("name"), primary_key=True, max_length=300)
address = models.CharField(_("address"), max_length=300, unique=False)
categories = models.CharField(_("category"), null=True, max_length=300, unique=False)
latitude = models.FloatField(_("latitude"), max_length=150, unique=False)
longitude = models.FloatField(_("longitude"), max_length=150, unique=False)
当我尝试迁移更改时,它会显示:
$ python manage.py makemigrations
No changes detected
如何将所有行导入数据库?
所以我可以证明主键是唯一的: conflicting rows
我想我找到了它显示错误的原因。由于某种原因,模型中的主键与 csv 中的不同列匹配。 order of columns is messed up
【问题讨论】:
-
unique约束用于name,而不是categories。 -
您创建的行具有相同的
name.主键必须是唯一的。 -
@WillemVanOnsem 是的,但是这两行有不同的名称。就像值相同的唯一两列是“纬度”和“经度”。
-
@KlausD。我的主键是唯一的,但无法导入它们。
-
@Shoreo:错误“唯一约束失败:myapi_venue.name”另有说明。
标签: python django sqlite django-models