我正在做一个使用 MySQL 作为数据库的 Django 项目,我必须从另一个数据库中获取一些数据来填充我的 Django 数据库表的一些字段。
我的学生 Django 模型是这样的:
class Student(models.Model):
#user = models.OneToOneField(User)
email = models.EmailField(blank=True, null=True)
email_verified = models.BooleanField(blank=True)
mobile = models.CharField(max_length=11, unique=True, blank=True, null=True)
mobile_verified = models.BooleanField(blank=True)
nickname = models.CharField(max_length=20, blank=True, null=True)
gender = models.PositiveSmallIntegerField(choices=GENDER_CHOICES,
null=True, blank=True)
level = models.PositiveSmallIntegerField(choices=STUDENT_LEVELS_CHOICES,
null=True, blank=True)
source = models.PositiveSmallIntegerField(choices=SOURCE_SITE, blank=True, null=True)
register_at = models.DateTimeField(blank=True, null=True)
enroll_at = models.DateTimeField(blank=True, null=True)
state = models.PositiveSmallIntegerField(choices=STUDENT_MAINTAIN_STATE, blank=True, null=True)
is_company_user = models.BooleanField(blank=True)
company_name = models.CharField(max_length=40, blank=True, null=True)
importance = models.PositiveSmallIntegerField(choices=IMPORTANCE_STATE, blank=True, null=True)
feature = models.PositiveSmallIntegerField(choices=USER_FEATURE, blank=True, null=True)
description = models.CharField(max_length=1000, blank=True, null=True)
sales = models.ForeignKey(User)
remaining = models.IntegerField(blank=True, null=True)#订单余额
last_state_change_time = models.DateTimeField(blank=True, null=True)
is_delete = models.BooleanField(blank=True, default=False)
objects = StudentManager()
def __unicode__(self):
return self.nickname
我写了一个py脚本来从另一个数据库传输数据,脚本是:
import MySQLdb
try:
conn = MySQLdb.connect(host='localhost', user='root', passwd='', db='a')
cur = conn.cursor()
cur.execute('select * from student;')
res = cur.fetchall()
cur.close()
conn.close()
conn = MySQLdb.connect(host='localhost', user='root', passwd='', db='b')
cur = conn.cursor()
for item in res:
if item:
cur.execute('insert into student_student (email, email_verified, mobile, mobile_verified, nickname, gender, level, register_at) values (%s, %s, %s, %s, %s, %s, %s, %s);', (item[3], item[4], item[1], item[2], item[7], item[8], item[6], item[14]))
conn.commit()
cur.close()
conn.close()
except MySQLdb.Error, e:
print "Mysql Error %d: %s" % (e.args[0], e.args[1])
我的目标是从“a”读取数据到“b”,b 的某些字段可能为空(因为 a 中只有几个字段适合 b)。当我运行脚本时,出现以下错误:
Mysql 错误 1452:无法添加或更新子行:外键约束失败(crm.student_student,CONSTRAINT sales_id_refs_id_6e3649f6 FOREIGN KEY (sales_id) REFERENCES auth_user (id))
如何解决这个问题?
我将存储引擎更改为 innodb,但它不起作用。