Home > Software engineering >  Cannot create a db from scratch after messing with squashmigrations command in django
Cannot create a db from scratch after messing with squashmigrations command in django

Time:11-17

I tried to run the squashmigrations command in django and after a while I needed to delete the db and start from scratch (the problem also applies when downloading the repository from GitHub and trying to recreate the project). I get the following error when running python manage.py makemigrations or python manage.py migrate

error:

(venv)  meal_plan   main  python manage.py makemigrations
Traceback (most recent call last):
  File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/db/backends/utils.py", line 89, in _execute
    return self.cursor.execute(sql, params)
  File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/db/backends/sqlite3/base.py", line 357, in execute
    return Database.Cursor.execute(self, query, params)
sqlite3.OperationalError: no such table: meal_plan_recipe

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/Users/enricobonardi/CODING/TESTING/meal_plan/manage.py", line 22, in <module>
    main()
  File "/Users/enricobonardi/CODING/TESTING/meal_plan/manage.py", line 18, in main
    execute_from_command_line(sys.argv)
  File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line
    utility.execute()
  File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 440, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/core/management/base.py", line 402, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/core/management/base.py", line 443, in execute
    self.check()
  File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/core/management/base.py", line 475, in check
    all_issues = checks.run_checks(
  File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/core/checks/registry.py", line 88, in run_checks
    new_errors = check(app_configs=app_configs, databases=databases)
  File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/core/checks/urls.py", line 42, in check_url_namespaces_unique
    all_namespaces = _load_all_namespaces(resolver)
  File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/core/checks/urls.py", line 61, in _load_all_namespaces
    url_patterns = getattr(resolver, "url_patterns", [])
  File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/utils/functional.py", line 57, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/urls/resolvers.py", line 715, in url_patterns
    patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
  File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/utils/functional.py", line 57, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/urls/resolvers.py", line 708, in urlconf_module
    return import_module(self.urlconf_name)
  File "/Users/enricobonardi/.pyenv/versions/3.10.7/lib/python3.10/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 688, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 883, in exec_module
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "/Users/enricobonardi/CODING/TESTING/meal_plan/config/urls.py", line 9, in <module>
    path("", include("meal_plan.urls", namespace="mealplan")),
  File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/urls/conf.py", line 38, in include
    urlconf_module = import_module(urlconf_module)
  File "/Users/enricobonardi/.pyenv/versions/3.10.7/lib/python3.10/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 688, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 883, in exec_module
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "/Users/enricobonardi/CODING/TESTING/meal_plan/meal_plan/urls.py", line 5, in <module>
    from . import views
  File "/Users/enricobonardi/CODING/TESTING/meal_plan/meal_plan/views.py", line 11, in <module>
    from .forms import MealPlanForm, RecipeSimpleForm
  File "/Users/enricobonardi/CODING/TESTING/meal_plan/meal_plan/forms.py", line 26, in <module>
    class RecipeSimpleForm(forms.ModelForm):
  File "/Users/enricobonardi/CODING/TESTING/meal_plan/meal_plan/forms.py", line 38, in RecipeSimpleForm
    RECIPES = [(x.id, x.title) for x in Recipe.objects.all()]
  File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/db/models/query.py", line 394, in __iter__
    self._fetch_all()
  File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/db/models/query.py", line 1866, in _fetch_all
    self._result_cache = list(self._iterable_class(self))
  File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/db/models/query.py", line 87, in __iter__
    results = compiler.execute_sql(
  File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/db/models/sql/compiler.py", line 1398, in execute_sql
    cursor.execute(sql, params)
  File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/db/backends/utils.py", line 103, in execute
    return super().execute(sql, params)
  File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/db/backends/utils.py", line 67, in execute
    return self._execute_with_wrappers(
  File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/db/backends/utils.py", line 80, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/db/backends/utils.py", line 84, in _execute
    with self.db.wrap_database_errors:
  File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/db/utils.py", line 91, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/db/backends/utils.py", line 89, in _execute
    return self.cursor.execute(sql, params)
  File "/Users/enricobonardi/CODING/TESTING/meal_plan/venv/lib/python3.10/site-packages/django/db/backends/sqlite3/base.py", line 357, in execute
    return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such table: meal_plan_recipe
(venv)  ✘  meal_plan   main  

I post the models.py that is being cited in the last line of the log:

meal_plan/models.py:

from django.conf import settings
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.urls import reverse

User = settings.AUTH_USER_MODEL


# ---------Stagionality----------#


class Month(models.Model):
    name = models.CharField(max_length=25)

    class Meta:
        ordering = ("id",)
        verbose_name = "mese"
        verbose_name_plural = "mesi"

    def __str__(self):
        return self.name


class VegetableItem(models.Model):
    class Types(models.IntegerChoices):
        VERDURA = 1
        FRUTTA = 2

    name = models.CharField(max_length=100)
    type = models.SmallIntegerField(choices=Types.choices, default=Types.VERDURA)
    description = models.TextField(blank=True)
    seasonality = models.ManyToManyField(Month, verbose_name="stagionalità")
    image = models.ImageField(upload_to="vegetableitems", default="vegetableitems/default.png")

    class Meta:
        verbose_name = "alimento stagionale"
        verbose_name_plural = "alimenti stagionali"

    def __str__(self):
        return self.name


# ---------END of Stagionality----------#

# ---------MealPlan----------#


class Day(models.TextChoices):
    LUNEDI = "LUN", "Lunedì"
    MARTEDI = "MAR", "Martedì"
    MERCOLEDI = "MER", "Mercoledì"
    GIOVEDI = "GIO", "Giovedì"
    VENERDI = "VEN", "Venerdì"
    SABATO = "SAB", "Sabato"
    DOMENICA = "DOM", "Domenica"


class Type(models.IntegerChoices):
    COLAZIONE = 1
    SPUNTINO = 2
    PRANZO = 3
    MERENDA = 4
    CENA = 5


class MealPlan(models.Model):
    title = models.CharField(max_length=100)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self) -> str:
        return self.title

    class Meta:
        verbose_name_plural = "mealplan"

    def get_absolute_url(self):
        return reverse("mealplan:mealplan_detail", kwargs={"pk": self.pk})


class Meal(models.Model):
    day = models.CharField(max_length=3, choices=Day.choices, default=Day.LUNEDI, verbose_name="giorno")
    type = models.IntegerField(choices=Type.choices)
    mealplan = models.ForeignKey(MealPlan, on_delete=models.CASCADE)

    class Meta:
        verbose_name = "pasto"
        verbose_name_plural = "pasti"

    def __str__(self) -> str:
        return f"{self.mealplan} ({self.get_day_display()} - {self.get_type_display()})"


class Measure(models.IntegerChoices):
    ML = 1
    G = 2
    UNIT = 3


class Recipe(models.Model):
    title = models.CharField(max_length=100)
    method = models.TextField(blank=True)
    meals = models.ManyToManyField(Meal)

    class Meta:
        verbose_name = "ricetta"
        verbose_name_plural = "ricette"

    def __str__(self) -> str:
        return self.title


class Ingredient(models.Model):
    name = models.CharField(max_length=100)
    quantity = models.SmallIntegerField(blank=True)
    measure = models.IntegerField(choices=Measure.choices, default=Measure.G)
    recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE, null=True)


@receiver(post_save, sender=MealPlan)
def mealplan_post_save_receiver(sender, instance, created, *args, **kwargs):
    if created:
        mealplan = instance
        days_of_the_week = Meal._meta.get_field("day").choices
        days = [label for label, day in days_of_the_week]
        for day in days:
            for type in range(1, 6):
                meal = Meal.objects.create(mealplan=mealplan, day=day, type=type)
                meal.save()


# ---------END of MealPlan----------#

I tried to reset migrations on the original repository using these instructions how-to-reset-migrations with no luck

Can anyone help me find the error?

CodePudding user response:

Simply delete your all migration folders and re-migrate manually using below command:

python manage.py makemigrations appname

python manage.py sqlmigrate appname 0001

python manage.py migrate

And see if it solves your error

CodePudding user response:

Finally found the bug causing the migration error. It's not about the squashmigrations command but in forms.py

class RecipeSimpleForm(forms.ModelForm):

...

RECIPES = [(x.id, x.title) for x in Recipe.objects.all()]

title = forms.ChoiceField(widget=forms.Select, choices=RECIPES)

class Meta:
    model = Recipe
    fields = ["title"]

I think the problem is I'm calling Recipe.objects.all() before the DB was created.

  • Related