简体   繁体   中英

Django migrations with foreign key

I' trying to migrate this model:

class Questionpart_image(models.Model):
    questionpart = models.ForeignKey(Questionpart, null=True, blank=True)
    image = models.ImageField()

to this:

class Questionpart_image(Questionpart): # notice this base class
    image = models.ImageField()

to make advantage of inheritance. Django produces the following migration:

class Migration(migrations.Migration):

dependencies = [
    ('ochsite', '0016_auto_20150809_1903'),
]

operations = [
    migrations.RemoveField(
        model_name='questionpart_image',
        name='id',
    ),
    migrations.RemoveField(
        model_name='questionpart_image',
        name='questionpart',
    ),
    migrations.AddField(
        model_name='questionpart_image',
        name='questionpart_ptr',
        field=models.OneToOneField(default='', primary_key=True, to='ochsite.Questionpart', serialize=False, parent_link=True, auto_created=True),
        preserve_default=False,
    ),
]

but this does not set the right foreign key to questionpart_ptr from questionpart field. How can I achieve that?
I've been searching for a long time, but nothing...thanks

Simply don't rely on automatic migrations, make your own or modify that one.

Simplest solution will be by moving AddField in migration to the top of the list and inject between it and RemoveField s RunPython block that will rewrite id's from old field to new (and in other direction in reverse, if needed).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM