0

I have 3 models:


class Series(models.Model):
    .
    .
    .
    series_name = models.CharField(max_length=50, unique=True)


class Lists(models.Model):
    .
    .
    name = models.CharField(max_length=50, unique=True)


class Article(models.Model):
    .
    .
    .
    lists = models.ForeignKey(Lists, blank=True, null=True, related_name='article_has', on_delete=models.CASCADE, default=None)
    series = models.ManyToManyField(Series, related_name='series', blank=True)
    is_published = models.BooleanField(default=False)

Initially I created some Articles without 'lists' field. Now i want to add the 'Lists' field to the Article model but I am running into errors after makemigrations and migrate.

I did the following:

  1. python manage.py makemigrations blog
  2. python manage.py migrate
  3. python manage.py makemigrations --empty blog
  4. modified the new empty generated migration file as follows:
# Generated by Django 4.0.3 on 2022-05-03 13:54

from django.db import migrations

def migrate_m2m_to_fk(apps, schema_editor):
    Article = apps.get_model("blog", "Article")
    for article in Article.objects.all():
        article.lists = None
        article.lists.save()

class Migration(migrations.Migration):

    dependencies = [
        ('blog', '0001_initial'),
    ]

    operations = [
        migrations.RunPython(migrate_m2m_to_fk)
    ]


  1. python manage.py migrate

and at the step 5 I get the following error due to Article.objects.all() :

MySQLdb._exceptions.OperationalError: (1054, "Unknown column 'blog_article.lists_id' in 'field list'")

christk
  • 834
  • 11
  • 23
  • Does this answer your question? [Django: Safely Remove Old Migrations?](https://stackoverflow.com/questions/58000680/django-safely-remove-old-migrations) – Ankit Tiwari May 04 '22 at 11:02

1 Answers1

0

You can use update() instead of looping over articles:

Article.objects.update(lists = None)

Also, it can be because of:

on_delete=models.CASCADE