我正在尝试向我不久前创建的 ManyToMany 字段添加订单。我基本上想在图片集中订购图片。我在 Django 1.7 上运行,所以不再向南迁移(我试图按照本教程进行操作:http: //mounirmesselmeni.github.io/2013/07/28/migrate-django-manytomany-field-to-manytomany-through -与南/)
这是我拥有的“通过”关系:
class CollectionPictures(models.Model):
picture = models.ForeignKey(
Picture,
verbose_name=u'Picture',
help_text=u'Picture is included in this collection.',
)
collection = models.ForeignKey(
Collection,
verbose_name=u'Collection',
help_text=u'Picture is included in this collection',
)
order = models.IntegerField(
verbose_name=u'Order',
help_text=u'What order to display this picture within the collection.',
max_length=255
)
class Meta:
verbose_name = u"Collection Picture"
verbose_name_plural = u"Collection Pictures"
ordering = ['order', ]
def __unicode__(self):
return self.picture.name + " is displayed in " + self.collection.name + (
" in position %d" % self.order)
class Collection(models.Model):
pictures = models.ManyToManyField(Picture, through='CollectionPictures', null=True)
[... Bunch of irrelevant stuff after]
因此,如果我不必迁移旧数据, 这应该可以工作(模型中唯一的区别是它没有through='CollectionPictures'
这是我的迁移:
class Migration(migrations.Migration):
dependencies = [
('artist', '0002_auto_20141013_1451'),
('business', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='CollectionPictures',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('order', models.IntegerField(help_text='What order to display this picture within the collection.', max_length=255, verbose_name='Order')),
('collection', models.ForeignKey(verbose_name='Collection', to='business.Collection', help_text='Picture is included in this collection')),
('picture', models.ForeignKey(verbose_name='Picture', to='artist.Picture', help_text='Picture is included in this collection.')),
],
options={
'ordering': ['order'],
'verbose_name': 'Collection Picture',
'verbose_name_plural': 'Collection Pictures',
},
bases=(models.Model,),
),
migrations.AlterField(
model_name='collection',
name='pictures',
field=models.ManyToManyField(to=b'artist.Picture', null=True, through='business.CollectionPictures'),
),
]
迁移时会引发错误:
ValueError:无法将字段 business.Collection.pictures 更改为 business.Collection.pictures - 它们不是兼容的类型(您无法更改 M2M 字段或从 M2M 字段更改,或通过 = 在 M2M 字段上添加或删除)
是否有人已经尝试过使用新的 1.7 迁移进行这种操作?
谢谢 !