Django - 将ManyToMany迁移到

时间:2016-11-09 17:42:10

标签: django django-migrations manytomanyfield

我的模型看起来像这样:

class Assignment(models.Model):
    """An assignment covers a range of years, 
    has multiple coders and one specific task"""
    title = models.CharField(blank=True, max_length=100)
    start_date = models.DateField(default=date.today)
    end_date = models.DateField(default=date.today)
    coders = models.ManyToManyField(User, related_name='assignments')

我想要更改此模型(已在生产中使用数据),使其看起来像这样:

class Assignment(models.Model):
    """An assignment covers a range of years, 
    has multiple coders and one specific task"""
    title = models.CharField(blank=True, max_length=100)
    start_date = models.DateField(default=date.today)
    end_date = models.DateField(default=date.today)
    coders = models.ManyToManyField(User, through = 'AssignmentProgress')

class AssignmentProgress(models.Model):
    """The progress a particular coder has made with an assignment"""
    assignment = models.ForeignKey(Assignment, related_name="assignment_progress")
    coder = models.ForeignKey(User, related_name="assignment_progress")
    articles_coded = models.IntegerField(default=0, null=False)
    progress = models.FloatField(default=0, null=False)

根据我到目前为止所阅读的内容,解决方案是将字段assignment_coders = models.ManyToManyField(User, through = 'AssignmentProgress')添加到Assignment,然后使用数据迁移来复制信息。

我尝试了以下数据迁移:

# -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-11-09 16:31
from __future__ import unicode_literals

from django.db import migrations

def move_coders(apps, schema_editor):
    # We can't import the Person model directly as it may be a newer
    # version than this migration expects. We use the historical version.
    Assignment = apps.get_model("coding", "Assignment")
    for a in Assignment.objects.all():
        a.assignment_coders = a.coders
        a.save()


class Migration(migrations.Migration):

    dependencies = [
        ('coding', '0006_auto_20161109_1730'),
    ]

    operations = [
        migrations.RunPython(move_coders),
    ]

但是当我尝试运行迁移时出现以下错误:Cannot set values on a ManyToManyField which specifies an intermediary model.

如何将Assignment.coders从ManyToMany字段迁移到through=的字段而不会丢失数据?

0 个答案:

没有答案
相关问题