Python 2.7 完整性错误-导入数据时get_或_create语句不能为NULL
我问我在哪里不知道如何正确使用外键。这一问题得到了很好的解决,尽管随后我遇到了关于django.db.utils.integrityyror:core_team.blahblah_id可能不为NULL的问题,我决定回滚,做一些稍微简单的事情-以避免重复查找(比赛链接到球队和联赛),我将编写一个管理命令来导入团队 根据我对上一个问题(显然有缺陷)的理解,我做得很好-它使用Python 2.7 完整性错误-导入数据时get_或_create语句不能为NULL,python-2.7,csv,model,django-south,django-1.5,Python 2.7,Csv,Model,Django South,Django 1.5,我问我在哪里不知道如何正确使用外键。这一问题得到了很好的解决,尽管随后我遇到了关于django.db.utils.integrityyror:core_team.blahblah_id可能不为NULL的问题,我决定回滚,做一些稍微简单的事情-以避免重复查找(比赛链接到球队和联赛),我将编写一个管理命令来导入团队 根据我对上一个问题(显然有缺陷)的理解,我做得很好-它使用get\u或\u create检查联赛实例,然后根据该实例分配球队。我还双重检查了DB是否是最新的(我正在向南跑,在上次更改方案
get\u或\u create
检查联赛实例,然后根据该实例分配球队。我还双重检查了DB是否是最新的(我正在向南跑,在上次更改方案时做了向前迁移,自那时以来没有任何变化。上次的变化是将两个模型中的名字作为主键(因为每个名字只有一支球队,每个名字只有一个联赛)
最近,我添加了代码,为团队get_或_create部分提供默认值,但收到了相同的错误。我理解错误的原因(我认为),即团队中的外键“league”已经存在于数据库中,并且不能为null插入另一个团队(从),只是不知道如何修复它
管理指挥部:
from django.core.management.base import BaseCommand, CommandError
import csv
import csvImporter
#from core.models import Match
from time import strptime
from datetime import datetime
master_data = open ('/Users/chris/Desktop/AllDataTruncated.csv', 'r')
data = list(tuple(rec) for rec in csv.reader(master_data, delimiter=','))
from core.models import League, Team
team_list = []
for row in data:
if row[2] == "HomeTeam":
print "Continuing"
continue
elif row[2] == "":
print "Continuing"
continue
else:
league, _ = League.objects.get_or_create(name=row[0])
print league
team, _ = Team.objects.get_or_create(team_name=row[2], defaults={'league':league})
current_team = Team(league = league, team_name=team)
print current_team
以及models.py的相关位:
class League (models.Model):
name = models.CharField(max_length=2, primary_key=True)
last_modified = models.CharField(max_length=50)
def __unicode__(self):
return unicode(self.name)
class Team(models.Model):
team_name = models.CharField(max_length=50, primary_key=True)
league = models.ForeignKey(League)
team_colour = models.CharField(max_length=6, null=True, blank=True)
def __unicode__(self):
return unicode (self.team_name)
完整回溯是:
$ python manage.py importteams
Continuing
E0
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/__init__.py", line 453, in execute_from_command_line
utility.execute()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/__init__.py", line 392, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/__init__.py", line 272, in fetch_command
klass = load_command_class(app_name, subcommand)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/management/__init__.py", line 77, in load_command_class
module = import_module('%s.management.commands.%s' % (app_name, name))
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/utils/importlib.py", line 35, in import_module
__import__(name)
File "/Users/chris/Dropbox/Django/gmblnew/core/management/commands/importteams.py", line 26, in <module>
team2, _ = Team.objects.get_or_create(team_name=row[3])
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/manager.py", line 146, in get_or_create
return self.get_query_set().get_or_create(**kwargs)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/query.py", line 487, in get_or_create
six.reraise(*exc_info)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/query.py", line 477, in get_or_create
obj.save(force_insert=True, using=self.db)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/base.py", line 546, in save
force_update=force_update, update_fields=update_fields)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/base.py", line 650, in save_base
result = manager._insert([self], fields=fields, return_id=update_pk, using=using, raw=raw)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/manager.py", line 215, in _insert
return insert_query(self.model, objs, fields, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/query.py", line 1661, in insert_query
return query.get_compiler(using=using).execute_sql(return_id)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 937, in execute_sql
cursor.execute(sql, params)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/backends/util.py", line 41, in execute
return self.cursor.execute(sql, params)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py", line 364, in execute
six.reraise(utils.IntegrityError, utils.IntegrityError(*tuple(e.args)), sys.exc_info()[2])
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py", line 362, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: core_team.league_id may not be NULL
这就是使这个问题长期存在的原因吗
编辑:似乎没有。删除了数据库并移动了South migrations文件夹,它仍然在这样做。源CSV也很好(没有空行或空字符串/段),上面的代码有一个部分可以跳过这些部分;它不会走得太远。呃。对于任何其他后来的新手来说,这个问题的答案其实非常简单。我在这里做的是在表“Team”中创建一个条目,它有一个返回到“League”的外键 “诀窍”(这不是一个诀窍,只是在文档中解释得很糟糕,imho)是当你为团队对象创建get_或_时,你需要显式地将联盟传递回去。这不仅仅是匹配团队名称 我以为我已经做到了,但似乎我没有做到。这段代码可以工作(并且非常有效地确保没有重复项):
你能放下你的数据库再试一次吗?这样做了,然后从一个完全空白的数据库开始(运行
syncdb
然后migrate
。migrate提供了…运行核心迁移:-迁移到0005\u auto\u del\u field\u team\u id\u chg\u field\u team\u team\u name\u add\u unique\u team\u tea.>核心:0001\u initial>core:0002\u auto\u chg\u field\u match\u客场\u目标上的投篮\u chg\u field\u match\u全场比赛\u全场比赛\u全场比赛\u全场比赛ay_shots_on_target____chg_field_match_full_time_
运行importItems之后会出现相同的错误:django.db.utils.IntegrityError:core_team.league_id可能不为空
这就是我,呃,“强烈不喜欢”的原因南方:迁移地狱。如果您的所有数据都是CSV格式,并且有一个导入程序可以使用:将您的迁移
目录移动到/tmp
或其他位置,从一个新的数据库开始,然后再试一次。如果修复了,请用fire杀死迁移目录。好的,尝试了,没有成功,同样的错误。值得注意的是-当我运行它时在空白数据库上,它正确地创建了一个新的联盟对象-在运行impportteams后,E0现在就在那里,在我尝试将一个团队分配给数据库时,它只是出错了。您的文件中是否有任何空行,或者行[0]
是'
的任何行?
? The field 'League.id' does not have a default specified, yet is NOT NULL.
? Since you are removing this field, you MUST specify a default
? value to use for existing rows. Would you like to:
? 1. Quit now.
? 2. Specify a one-off value to use for existing columns now
? 3. Disable the backwards migration by raising an exception; you can edit the migration to fix it later
? Please select a choice: 3
for row in data:
if row[2] == "HomeTeam":
print "Continuing"
continue
elif row[2] == "":
print "Continuing"
continue
else:
league, _ = League.objects.get_or_create(name=row[0])
print league
team, _ = Team.objects.get_or_create(team_name=row[2], league=league)
current_team = Team(league = league, team_name=team)
print current_team