将Django数据迁移到新表中

1 投票
1 回答
2143 浏览
提问于 2025-04-17 15:09

我有一个活动表,里面有两种不同类型的参与者,分别是工作人员和学生。我想把这些参与者放在一个单独的表里。

活动表里包含:

     created = models.DateTimeField(auto_now_add=True)
     modified = models.DateTimeField(auto_now=True)
     name = models.CharField(max_length=200)
     location = models.CharField(max_length=200)
     start_date = models.DateTimeField(auto_now=False, auto_now_add=False)
     about = models.TextField(null=True, blank=True)

     student_attendees = models.ManyToManyField(StudentProfile, null=True, blank=True)
     staff_attendees = models.ManyToManyField(StaffProfile, null=True, blank=True)

参与者表里会有:

     event = models.ForeignKey(Event)
     content_type = models.ForeignKey(ContentType)
     object_id = models.PositiveIntegerField()
     profile = generic.GenericForeignKey('content_type', 'object_id')
     created = models.DateTimeField(auto_now_add=True)

我该如何把活动中的学生和工作人员的数据转移到自己的参与者表里呢?(我不想使用South,现在也想避免使用它。)谢谢你的帮助和建议。

1 个回答

3

你可以把数据放到json格式里,然后手动把它们分成不同的部分,再修改表格(或者重新创建数据库)并加载这些数据。

或者你可以写个脚本,手动选择一些字段,把它们保存成pickle格式,或者手动保存成json,甚至是CSV格式:

with open('students.csv', 'w') as st_file:
    writer = csv.writer(st_file)
    for a in Attendee.objects.filter(profile__status='student'):
        st_file.writerow(a.event_id, a.content_type, a.object_id, a.profile, ...)

然后写一个简单的脚本来加载这些数据。

with open('students.csv', 'w') as st_file:
    reader = csv.reader(st_file)
    for row in reader:
        event = Event.objects.get(id=row[0])
        event.student_attendees.add(Student.objects.get(row[2]))

(这意味着object_id和StudentProfile表里的新id是一样的)

当然,在做这些之前,记得先备份数据库。

其实,还有更好的方法:

 python manage.py dumpdata app.event app.attendee --indent=4 > events.json

然后编辑以适应新的表格,接着

 python manage.py loaddata events.json

撰写回答