将django数据移动/迁移到新表中

时间:2013-02-07 20:48:13

标签: python django django-models

我有一个事件表。我有2种不同类型的与会者,员工和学生。我想做的是让与会者参加一个特殊的表格。

事件表包含:

     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)

我如何转移或迁移活动学生&员工将参与者数据放入其自己的参加者表中。 (我不使用南方,此时想避免使用它。)感谢您的帮助和建议。

1 个答案:

答案 0 :(得分:3)

您可以将数据转储到json中并手动将它们分成不同的夹具,然后更改表(或重新创建数据库)并加载数据。

或者只是编写一个脚本来手动选择一些字段并将它们腌制或手动转储为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
相关问题