提问者:小点点

如何从csv用外键填充django模型


我的model.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')

生成的exeption:

文件"C:\用户\Wynt\AppData\local\conda\conda\envs\DjangoEnv\lib\site-包\django\db\backend\utils.py",第85行,_execute返回self.cursor.execute(sql,params)
文件"C:\用户\Wynt\AppData\local\conda\conda\envs\DjangoEnv\lib\site-包\django\db\utils.py",第89行,__exit__raisendj_exc_value.with_traceback(回溯),来自exc_value
File"C:\用户\Wynt\AppData\local\conda\conda\envs\DjangoEnv\lib\site-包\django\db\后端\utils.py",第85行,在_execute中返回self.cursor.execute(sql, params)
File"C:\用户\Wynt\AppData\local\conda\conda\envs\DjangoEnv\lib\site-包\django\db\后端\sqlite3\base.py",第303行,在执行返回数据库中。Cursor.execute(自我,查询,参数)django.db.utils.完整性错误:非空约束失败:basic_app_teams.category_id


共1个答案

匿名用户

>

  • 确保在创建Teams对象时,类别永远不会是空的,即行[4]中来自csv的值。换句话说,如果行[4]在任何时间点都是空的,它将引发异常,因为在模型类别中是一个强制性外键

    类别=模型。on_delete=模型。CASCADE,null=True,Black=True)
    或在创建Teams对象时确保类别的值从不为空