Django 1.7 migrations: django.db.utils.OperationalError: no such table: db_trans_language

三世轮回 提交于 2019-12-25 03:32:25

问题


I'm working on a django project and have had some migration troubles in my (test)prod setting and as a consequence have I dumped all relevant data and I am now in the process of setting up the database from scratch.

Here is what happens:

  1. I remove all (potentially) faulty migrations from the app
  2. I run makemigrations
  3. I run migrate
  4. I am presented with the following error:

Error:

C:\Users\Sverker\Dropbox\Picrates>python manage.py makemigrations db_trans
C:\Users\Sverker\Dropbox\Picrates\picrates_project
Migrations for 'db_trans':
  0001_initial.py:
    - Create model Language
    - Create model Markup
    - Create model String
    - Create model TransMarkup
    - Create model TransString
    - Add field trans_string to string
    - Alter unique_together for string (1 constraint(s))
    - Add field trans_markup to markup
    - Alter unique_together for markup (1 constraint(s))

C:\Users\Sverker\Dropbox\Picrates>python manage.py migrate
C:\Users\Sverker\Dropbox\Picrates\picrates_project
Operations to perform:
  Synchronize unmigrated apps: allauth, linkedin_oauth2, crispy_forms
  Apply all migrations: account, sessions, admin, db_trans, sites, auth, contenttypes, parties, ped, socialaccount
Synchronizing apps without migrations:
  Creating tables...
  Installing custom SQL...
  Installing indexes...
Running migrations:
  Applying db_trans.0001_initial...Traceback (most recent call last):
  File "manage.py", line 15, in <module>
    execute_from_command_line(sys.argv)
  File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 385, in execute_from_command_line
    utility.execute()
  File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 377, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Python27\lib\site-packages\django\core\management\base.py", line 288, in run_from_argv
    self.execute(*args, **options.__dict__)
  File "C:\Python27\lib\site-packages\django\core\management\base.py", line 338, in execute
    output = self.handle(*args, **options)
  File "C:\Python27\lib\site-packages\django\core\management\commands\migrate.py", line 161, in handle
    executor.migrate(targets, plan, fake=options.get("fake", False))
  File "C:\Python27\lib\site-packages\django\db\migrations\executor.py", line 68, in migrate
    self.apply_migration(migration, fake=fake)
  File "C:\Python27\lib\site-packages\django\db\migrations\executor.py", line 102, in apply_migration
    migration.apply(project_state, schema_editor)
  File "C:\Python27\lib\site-packages\django\db\migrations\migration.py", line 108, in apply
    operation.database_forwards(self.app_label, schema_editor, project_state, new_state)
  File "C:\Python27\lib\site-packages\django\db\migrations\operations\models.py", line 36, in database_forwards
    schema_editor.create_model(model)
  File "C:\Python27\lib\site-packages\django\db\backends\schema.py", line 213, in create_model
    definition, extra_params = self.column_sql(model, field)
  File "C:\Python27\lib\site-packages\django\db\backends\schema.py", line 125, in column_sql
    default_value = self.effective_default(field)
  File "C:\Python27\lib\site-packages\django\db\backends\schema.py", line 175, in effective_default
    default = field.get_default()
  File "C:\Python27\lib\site-packages\django\db\models\fields\__init__.py", line 719, in get_default
    return self.default()
  File "C:\Users\Sverker\Dropbox\Picrates\db_trans\models.py", line 9, in get_default_priority
    max = Language.objects.all().aggregate(models.Max("fallback_priority"))["fallback_priority__max"]
  File "C:\Python27\lib\site-packages\django\db\models\query.py", line 325, in aggregate
    return query.get_aggregation(using=self.db, force_subq=force_subq)
  File "C:\Python27\lib\site-packages\django\db\models\sql\query.py", line 402, in get_aggregation
    result = query.get_compiler(using).execute_sql(SINGLE)
  File "C:\Python27\lib\site-packages\django\db\models\sql\compiler.py", line 786, in execute_sql
    cursor.execute(sql, params)
  File "C:\Python27\lib\site-packages\django\db\backends\utils.py", line 81, in execute
    return super(CursorDebugWrapper, self).execute(sql, params)
  File "C:\Python27\lib\site-packages\django\db\backends\utils.py", line 65, in execute
    return self.cursor.execute(sql, params)
  File "C:\Python27\lib\site-packages\django\db\utils.py", line 94, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "C:\Python27\lib\site-packages\django\db\backends\utils.py", line 65, in execute
    return self.cursor.execute(sql, params)
  File "C:\Python27\lib\site-packages\django\db\backends\sqlite3\base.py", line 485, in execute
    return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such table: db_trans_language

Here is the created migration:

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations
import markupfield.fields
import db_trans.models


class Migration(migrations.Migration):

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Language',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('code', models.CharField(max_length=3)),
                ('language', models.CharField(max_length=50)),
                ('is_public', models.BooleanField(default=False)),
                ('fallback_priority', models.PositiveIntegerField(default=db_trans.models.get_default_priority, help_text=b'Lowest value will be first fallback language.', unique=True)),
            ],
            options={
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='Markup',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('markup', markupfield.fields.MarkupField()),
                ('markup_markup_type', models.CharField(default=b'markdown', max_length=30, editable=False, choices=[(b'', b'--'), (b'html', b'html'), (b'plain', b'plain'), (b'markdown', b'markdown')])),
                ('_markup_rendered', models.TextField(editable=False)),
                ('language', models.ForeignKey(to='db_trans.Language')),
            ],
            options={
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='String',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('string', models.CharField(max_length=256)),
                ('language', models.ForeignKey(to='db_trans.Language')),
            ],
            options={
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='TransMarkup',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('key', models.CharField(unique=True, max_length=50, db_index=True)),
                ('verbose_name', models.CharField(max_length=200, null=True, blank=True)),
            ],
            options={
                'verbose_name': 'Translated Markup',
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='TransString',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('key', models.CharField(unique=True, max_length=50, db_index=True)),
                ('verbose_name', models.CharField(max_length=200, null=True, blank=True)),
            ],
            options={
                'verbose_name': 'Translated String',
            },
            bases=(models.Model,),
        ),
        migrations.AddField(
            model_name='string',
            name='trans_string',
            field=models.ForeignKey(related_name='strings', to='db_trans.TransString'),
            preserve_default=True,
        ),
        migrations.AlterUniqueTogether(
            name='string',
            unique_together=set([('trans_string', 'language')]),
        ),
        migrations.AddField(
            model_name='markup',
            name='trans_markup',
            field=models.ForeignKey(related_name='markups', to='db_trans.TransMarkup'),
            preserve_default=True,
        ),
        migrations.AlterUniqueTogether(
            name='markup',
            unique_together=set([('trans_markup', 'language')]),
        ),
    ]

models.py:

from django.db import models
from django.template.loader import render_to_string
from django.utils.translation import get_language
from markupfield.fields import MarkupField


def get_default_priority():
    max = Language.objects.all().aggregate(models.Max("fallback_priority"))["fallback_priority__max"]
    if max:
        return max + 10
    return 50


class Language(models.Model):
    code = models.CharField(
        max_length=3,
        null=False,
        blank=False,
    )

    language = models.CharField(
        max_length=50,
    )

    is_public = models.BooleanField(
        default=False,
    )

    fallback_priority = models.PositiveIntegerField(
        null=False,
        unique=True,
        default=get_default_priority,
        help_text="Lowest value will be first fallback language."
    )

    def __unicode__(self):
        unicode = self.code
        if self.language:
            unicode += u" - " + self.language
        return unicode


class TransPhrase(models.Model):
    key = models.CharField(
        max_length=50,
        unique=True,
        null=False,
        blank=False,
        db_index=True,
    )

    verbose_name = models.CharField(
        max_length=200,
        null=True,
        blank=True,
    )

    @classmethod
    def get_translation(cls, key, description=None):
        trans_phrase, created = cls.objects.get_or_create(key=key)
        if not description:
            trans_phrase.verbose_name = description
            trans_phrase.save()
        return trans_phrase


    def render(self, wrap, csrf_token):
        raise NotImplementedError

    class Meta:
        abstract = True


class TransMarkup(TransPhrase):
    def get_trans(self, language_code, use_fallback=True):
        try:
            return self.markups.get(language__code=language_code)
        except Markup.DoesNotExist:
            if use_fallback:
                fallback_markups = self.markups.all().order_by("language__fallback_priority")
                if fallback_markups:
                    return fallback_markups[0]

            language = Language.objects.get(code=language_code)
            return Markup(trans_markup=self, language=language)

    def __unicode__(self):
        return u"[" + self.key + u"]"

    def render(self, wrap, csrf_token):
        from db_trans.forms import SetTransMarkupForm

        markup = self.get_trans(get_language(), use_fallback=(not wrap))
        if wrap:
            context = {
                "csrf_token": csrf_token,
                "form": SetTransMarkupForm(instance=markup),
                "trans_markup": markup
            }
            return render_to_string("db_trans/set_markup.html", context)
        else:
            return markup

    class Meta:
        verbose_name = "Translated Markup"


class Markup(models.Model):
    markup = MarkupField(
        markup_type="markdown"
    )

    trans_markup = models.ForeignKey(
        TransMarkup,
        null=False,
        related_name="markups",
    )

    language = models.ForeignKey(
        Language,
        null=False,
    )

    def __unicode__(self):
        if self.markup.rendered:
            return self.markup.rendered
        return u"[" + self.trans_markup.key + u"]"

    class Meta:
        unique_together = ("trans_markup", "language")


class TransString(TransPhrase):
    def get_trans(self, language_code, use_fallback=True):
        try:
            return self.strings.get(language__code=language_code)
        except String.DoesNotExist:
            if use_fallback:
                fallback_strings = self.strings.all().order_by("language__fallback_priority")
                if fallback_strings:
                    return fallback_strings[0]

            language = Language.objects.get(code=language_code)
            return String(trans_string=self, language=language)


    def render(self, wrap, csrf_token):
        from db_trans.forms import SetTransStringForm

        string = self.get_trans(get_language(), use_fallback=(not wrap))
        if wrap:
            context = {
                "csrf_token": csrf_token,
                "form": SetTransStringForm(instance=string),
                "trans_string": string
            }
            return render_to_string("db_trans/set_string.html", context)
        else:
            return string

    class Meta:
        verbose_name = "Translated String"


class String(models.Model):
    string = models.CharField(
        max_length=256
    )

    trans_string = models.ForeignKey(
        TransString,
        null=False,
        related_name="strings"
    )

    language = models.ForeignKey(
        Language,
        null=False,
    )

    def __unicode__(self):
        if self.string:
            return self.string
        return u"[" + self.trans_string.key + u"]"

    class Meta:
        unique_together = ("trans_string", "language")

Help would be greatly appreciated!


回答1:


I know this is an old question, but I recently had a similar error. The offensive line is probably:

File "C:\Users\Sverker\Dropbox\Picrates\db_trans\models.py", line 9, in get_default_priority
  max = Language.objects.all().aggregate(models.Max("fallback_priority"))["fallback_priority__max"]

So here, you are querying the database with Language.objects.all(). This line gets executed before the migrations are actually run, while there's still inconsistency between models.py and the database itself.

Try commenting out that line (and other references to max), and then re-run the migrations. That's what worked for me.



来源:https://stackoverflow.com/questions/29963186/django-1-7-migrations-django-db-utils-operationalerror-no-such-table-db-trans

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!