相关疑难解决方法(0)

如何通过django中的迁移和数据向现有ManyToManyField添加选项

我无法在文档或在线中找到对特定问题的引用.

我有很多关系.

class Books(models.Model):
    name = models.CharField(max_length=100)

class Authors(models.Model):
    name = models.CharField(max_length=100)
    books = models.ManyToManyField(Books)
Run Code Online (Sandbox Code Playgroud)

这有迁移和数据.现在我需要使用through选项,以便在表中添加一个包含多对多关系的额外字段.

class Authorship(models.Model):
    book = models.ForeignKey(Books)
    author = models.ForeignKey(Authors)
    ordering = models.PositiveIntegerField(default=1)

class Authors(models.Model):
    name = models.CharField(max_length=100)
    books = models.ManyToManyField(Books, through=Authorship)
Run Code Online (Sandbox Code Playgroud)

当我运行迁移时,django会为Authorship模型创建新的迁移.我尝试通过orderingAuthorship表中添加列并在表中更改books列来手动创建迁移文件,Authors但是我遇到了一些迁移问题.

operations = [
    migrations.AddField(
        model_name='authorship',
        name='ordering',
        field=models.PositiveIntegerField(default=1),
    ),
    migrations.AlterField(
        model_name='authors',
        name='books',
        field=models.ManyToManyField(to='app_name.Books', through='app_name.Authorship'),
    ),
]
Run Code Online (Sandbox Code Playgroud)

在尝试迁移时,KeyError: ('app_name', u'authorship')我认为还有其他因素会受到影响,从而导致错误.

我错过了什么?有没有其他方法可以解决这个问题?

django django-models django-migrations

20
推荐指数
2
解决办法
4426
查看次数

标签 统计

django ×1

django-migrations ×1

django-models ×1