Migrating data from “Many-To-Many” to “Many-To-Many Through” in django

前端 未结 4 1792
被撕碎了的回忆
被撕碎了的回忆 2020-12-29 06:47

I\'ve got a model

class Category(models.Model):
    title           = models.CharField(...)
    entry           = models.ManyToManyField(Entry,null=True,blan         


        
4条回答
  •  有刺的猬
    2020-12-29 07:34

    In Django 1.7+ built-in migrations, the way the "code state" (i.e. the code definition of models) is calculated is different, and requires a different solution.

    In South (Django pre-1.7), the entire "code state" is saved in each migration — but in Django 1.7+ built-in migrations, it's derived from looking at the whole set of migrations, so you need to specify the "code state" change in a migration without altering the database.

    Like above, this will need to be done in a few steps.

    1. Create an intermediate model like in the answer above:

      class CategoryEntry(models.Model):
          category = models.ForeignKey(Category, on_delete=models.CASCADE)
          entry = models.ForeignKey(Entry, on_delete=models.CASCADE)   
      
          class Meta:
               db_table = 'main_category_entries'   #change main_ to your application
               unique_together = ('category', 'entry')
      
    2. Create an auto-migration with django-admin.py makemigrations and modify the code; move the operations list into the state_operations argument of a migrations.SeparateDatabaseAndState operation, and leave the database_operations list empty. It should look like:

      class Migration(migrations.Migration):
          operations = [
              migrations.SeparateDatabaseAndState(
                  state_operations=[ 
                      migrations.CreateModel(CategoryEntry..)
                      ...
                  ],
                  database_operations=[]
              ),
          ]
      
    3. Edit the CategoryEntry to contain what you want and create a new auto-migration with django-admin.py makemigrations

提交回复
热议问题