python - 如何使用来自 csv 的外键填充 django 模型
问题描述
我的模型.py:
# Riders models ----------------------------------------
class CategoryTeam(models.Model):
name = models.CharField(max_length = 256)
def __str__(self):
return self.name
class Teams(models.Model):
name = models.CharField(max_length = 256)
code = models.CharField(max_length = 10)
nation = models.CharField(max_length = 10)
continent = models.CharField(max_length = 10)
category = models.ForeignKey(CategoryTeam, on_delete=models.CASCADE,)
def __str__(self):
return self.name
#-----------------------------------------------------#
我要填充的脚本
from basic_app.models import CategoryTeam,Teams
def populateCat():
f = open('CategoryCSV.csv')
reader = csv.reader(f)
next(reader)
for row in reader:
# Create new User Entry
category = CategoryTeam.objects.get_or_create(name=row[0])[0]
def populateTeamat():
f = open('FantaDS Project - Teams.csv')
reader = csv.reader(f)
next(reader)
for row in reader:
# Create new User Entry
team = Teams.objects.get_or_create(
name = row[0],
code = row[1],
nation = row[2],
continent = row[3],
category = row[4]
)[0]
if __name__ == '__main__':
print("Populating the databases Cat...Please Wait")
populateCat()
print('Populating Complete')
print("Populating the databases Team...Please Wait")
populateTeamat()
print('Populating Complete')
生成的异常:
_execute 中的文件“C:\Users\Wynt\AppData\Local\conda\conda\envs\DjangoEnv\lib\site-packages\django\db\backends\utils.py”,第 85 行,返回 self.cursor.execute( sql, params)
文件“C:\Users\Wynt\AppData\Local\conda\conda\envs\DjangoEnv\lib\site-packages\django\db\utils.py”,第 89 行,在 __exit__raise ndj_exc_value.with_traceback(traceback ) 来自 exc_value
文件“C:\Users\Wynt\AppData\Local\conda\conda\envs\DjangoEnv\lib\site-packages\django\db\backends\utils.py”,第 85 行,_execute return self.cursor .execute(sql, params)
文件“C:\Users\Wynt\AppData\Local\conda\conda\envs\DjangoEnv\lib\site-packages\django\db\backends\sqlite3\base.py”,第 303 行,在执行返回 Database.Cursor.execute(self, query, params) django.db.utils.IntegrityError: NOT NULL 约束失败:basic_app_teams.category_id
解决方案
确保在创建 Teams 对象时,类别永远不会为空,即来自行 [4] 处的 csv 的值。换句话说,如果 row[4] 在任何时候都为空,它将抛出异常,因为在 Model 类别中是强制外键。要么成功
category = models.ForeignKey(CategoryTeam, on_delete=models.CASCADE, null=True, black=True)
或者在创建 Teams 对象时确保类别的值永远不会为空
推荐阅读
- sql - 如何将 SQL 语句转换为 LINQ?
- java - 使用扫描仪 hasNext 方法进行 Infinity while 循环
- r - Power BI / R - 有没有办法在 Power BI 制作的 R 可视化中将两个未链接的表作为两个单独的对象读取?
- node.js - 努力绕过 Canvas 命令失败
- migration - 将数据从 apache gridgain 迁移到 ignite
- azure-functions - Azure Function Service Bus 触发蓝绿部署
- hotchocolate - 如何从自定义属性返回未经授权的结果?
- javascript - JavaScript Date 构造函数在 CMS(服务器端 JS)中返回无效日期
- validation - 如何在 Ajax.BeginForm 中验证 Kendo DateTimePickerFor?
- html - Lexbor:用 C 语言抓取 HTML 表格