首页 > 解决方案 > 如何使用来自 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

标签: pythondjangodjango-models

解决方案


  1. 确保在创建 Teams 对象时,类别永远不会为空,即来自行 [4] 处的 csv 的值。换句话说,如果 row[4] 在任何时候都为空,它将抛出异常,因为在 Model 类别中是强制外键。要么成功

    category = models.ForeignKey(CategoryTeam, on_delete=models.CASCADE, null=True, black=True)
    或者在创建 Teams 对象时确保类别的值永远不会为空


推荐阅读