django.db.utils.ProgrammingError:关系“bookmarks_article”已经存在; django app

时间:2016-03-10 03:19:02

标签: python django migration database-migration

我收到的奇怪的迁移错误:

django.db.utils.ProgrammingError: relation "bookmarks_article" already exists; 

我不明白为什么如果它存在,它会再次尝试制作表格。我刚刚删除了迁移文件并重新编写了makemigrations。我现在有

root@bookmarkbuddy:/home/django/bookwormbuddy# ./manage.py makemigrations
/usr/lib/python2.7/dist-packages/south/modelsinspector.py:17: RemovedInDjango19Warning: django.contrib.contenttypes.generic is deprecated and will be removed in Django 1.9. Its contents have been moved to the fields, forms, and admin submodules of django.contrib.contenttypes.
  from django.contrib.contenttypes import generic

System check identified some issues:

WARNINGS:
helpdesk.EscalationExclusion.queues: (fields.W340) null has no effect on ManyToManyField.
helpdesk.IgnoreEmail.queues: (fields.W340) null has no effect on ManyToManyField.
helpdesk.PreSetReply.queues: (fields.W340) null has no effect on ManyToManyField.
Migrations for 'bookmarks':
  0001_initial.py:
    - Create model Article
    - Create model ArticleTopic
    - Create model MyMpttTag
    - Create model MyTaggedManager
    - Create model Topic
    - Add field topic to articletopic
    - Add field tags to article
    - Add field user to article
    - Alter unique_together for articletopic (1 constraint(s))
root@bookmarkbuddy:/home/django/bookwormbuddy# ./manage.py migrate
/usr/lib/python2.7/dist-packages/south/modelsinspector.py:17: RemovedInDjango19Warning: django.contrib.contenttypes.generic is deprecated and will be removed in Django 1.9. Its contents have been moved to the fields, forms, and admin submodules of django.contrib.contenttypes.
  from django.contrib.contenttypes import generic

System check identified some issues:

WARNINGS:
helpdesk.EscalationExclusion.queues: (fields.W340) null has no effect on ManyToManyField.
helpdesk.IgnoreEmail.queues: (fields.W340) null has no effect on ManyToManyField.
helpdesk.PreSetReply.queues: (fields.W340) null has no effect on ManyToManyField.
Operations to perform:
  Synchronize unmigrated apps: spaces, mptt, staticfiles, messages, widget_tweaks, lists, django_extensions, bootstrapform, crispy_forms
  Apply all migrations: sessions, admin, helpdesk, auth, contenttypes, taggit, bookmarks
Synchronizing apps without migrations:
  Creating tables...
    Running deferred SQL...
  Installing custom SQL...
Running migrations:
  Rendering model states... DONE
  Applying bookmarks.0001_initial...Traceback (most recent call last):
  File "./manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
    utility.execute()
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 330, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 393, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 444, in execute
    output = self.handle(*args, **options)
  File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/migrate.py", line 221, in handle
    executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial)
  File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 110, in migrate
    self.apply_migration(states[migration], migration, fake=fake, fake_initial=fake_initial)
  File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 148, in apply_migration
    state = migration.apply(state, schema_editor)
  File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/migration.py", line 115, in apply
    operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
  File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/operations/models.py", line 59, in database_forwards
    schema_editor.create_model(model)
  File "/usr/local/lib/python2.7/dist-packages/django/db/backends/base/schema.py", line 286, in create_model
    self.execute(sql, params or None)
  File "/usr/local/lib/python2.7/dist-packages/django/db/backends/base/schema.py", line 111, in execute
    cursor.execute(sql, params)
  File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 79, in execute
    return super(CursorDebugWrapper, self).execute(sql, params)
  File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
  File "/usr/local/lib/python2.7/dist-packages/django/db/utils.py", line 97, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 62, in execute
    return self.cursor.execute(sql)
django.db.utils.ProgrammingError: relation "bookmarks_article" already exists

models.py:

from django.db import models
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse

import mptt
from mptt.models import MPTTModel, TreeForeignKey
from taggit.managers import TaggableManager
from taggit.models import TagBase, GenericTaggedItemBase
from taggit.utils import require_instance_manager

#----------------------------------------------------------------------------------------------------

class ArticleQueryset(models.query.QuerySet):
    def archived(self):
        return self.filter(archived=True)
    def current(self):
        return self.filter(archived=False)
    def category(self, this_category):
        return self.filter(category=this_category)
    def all_categories(self):
        categories = self.values('category').distinct()
        filtered_categories = [this_dict['category'] for this_dict in categories if this_dict['category']]
        return filtered_categories

#----------------------------------------------------------------------------------------------------

class ArticleManager(models.Manager):
    def get_queryset(self):
        return ArticleQueryset(self.model, using=self._db)
    def archived(self):
        return self.get_queryset().archived()
    def current(self):
        return self.get_queryset().current()
    def category(self):
        return self.get_queryset().category()
    def all_categories(self):
        return self.get_queryset().all_categories()

#----------------------------------------------------------------------------------------------------


class MyTag(TagBase):
    user = models.ForeignKey(User)

    class Meta:
        abstract = True

#----------------------------------------------------------------------------------------------------

class MyMpttTag(MPTTModel, MyTag):
    parent      = TreeForeignKey('self', null=True, blank=True, related_name='children')

    class MPTTMeta:
        parent_attr         = 'parent'

    def __unicode__(self):
        return self.slug

    def save(self, *args, **kwargs):
        slugged_name    = self.slugify(self.name)
        self.name       = slugged_name
        super(MyMpttTag, self).save( *args, **kwargs)

# #----------------------------------------------------------------------------------------------------

class MyTaggedManager(GenericTaggedItemBase):
    tag = models.ForeignKey(MyMpttTag, related_name="%(app_label)s_%(class)s_items")

#----------------------------------------------------------------------------------------------------

class Article(models.Model):
    url             = models.CharField(max_length=256, unique=True)
    title           = models.CharField(max_length=256, default="None", blank=True)
    created         = models.DateTimeField(auto_now_add=True)
    last_read       = models.DateTimeField(null=True, blank=True)
    viewed_count    = models.IntegerField(default=0)
    archived        = models.BooleanField(default=False, blank=True)
    user            = models.ForeignKey(User, null=True, blank=True)

    def __unicode__(self):
        return self.title

    def archive(self):
        self.archived = True
        self.save()

    def unarchive(self):
        self.archived = False
        self.save()

    objects = ArticleManager()

    tags = TaggableManager(through=MyTaggedManager)

    def get_absolute_url(self):
        return reverse('bookmarks:silo')

#----------------------------------------------------------------------------------------------------

class Topic(models.Model):
    title       = models.CharField(max_length=256)
    description = models.TextField(null=True, blank=True)

#----------------------------------------------------------------------------------------------------

class ArticleTopic(models.Model):
    class Meta:
        unique_together = (('topic', 'article',))

    topic   = models.ForeignKey('bookmarks.Topic')
    article = models.ForeignKey('bookmarks.Article')

迁移:

root@bookmarkbuddy:/home/django/bookwormbuddy/bookmarks/migrations# ls
0001_initial.py  0001_initial.pyc  __init__.py  __init__.pyc
root@bookmarkbuddy:/home/django/bookwormbuddy/bookmarks/migrations# cat 0001_initial.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations
import mptt.fields
from django.conf import settings
import taggit.managers


class Migration(migrations.Migration):

    dependencies = [
        ('contenttypes', '0002_remove_content_type_name'),
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name='Article',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('url', models.CharField(unique=True, max_length=256)),
                ('title', models.CharField(default=b'None', max_length=256, blank=True)),
                ('created', models.DateTimeField(auto_now_add=True)),
                ('last_read', models.DateTimeField(null=True, blank=True)),
                ('viewed_count', models.IntegerField(default=0)),
                ('archived', models.BooleanField(default=False)),
            ],
        ),
        migrations.CreateModel(
            name='ArticleTopic',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('article', models.ForeignKey(to='bookmarks.Article')),
            ],
        ),
        migrations.CreateModel(
            name='MyMpttTag',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('name', models.CharField(unique=True, max_length=100, verbose_name='Name')),
                ('slug', models.SlugField(unique=True, max_length=100, verbose_name='Slug')),
                ('lft', models.PositiveIntegerField(editable=False, db_index=True)),
                ('rght', models.PositiveIntegerField(editable=False, db_index=True)),
                ('tree_id', models.PositiveIntegerField(editable=False, db_index=True)),
                ('level', models.PositiveIntegerField(editable=False, db_index=True)),
                ('parent', mptt.fields.TreeForeignKey(related_name='children', blank=True, to='bookmarks.MyMpttTag', null=True)),
                ('user', models.ForeignKey(to=settings.AUTH_USER_MODEL)),
            ],
            options={
                'abstract': False,
            },
        ),
        migrations.CreateModel(
            name='MyTaggedManager',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('object_id', models.IntegerField(verbose_name='Object id', db_index=True)),
                ('content_type', models.ForeignKey(related_name='bookmarks_mytaggedmanager_tagged_items', verbose_name='Content type', to='contenttypes.ContentType')),
                ('tag', models.ForeignKey(related_name='bookmarks_mytaggedmanager_items', to='bookmarks.MyMpttTag')),
            ],
            options={
                'abstract': False,
            },
        ),
        migrations.CreateModel(
            name='Topic',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('title', models.CharField(max_length=256)),
                ('description', models.TextField(null=True, blank=True)),
            ],
        ),
        migrations.AddField(
            model_name='articletopic',
            name='topic',
            field=models.ForeignKey(to='bookmarks.Topic'),
        ),
        migrations.AddField(
            model_name='article',
            name='tags',
            field=taggit.managers.TaggableManager(to='bookmarks.MyMpttTag', through='bookmarks.MyTaggedManager', help_text='A comma-separated list of tags.', verbose_name='Tags'),
        ),
        migrations.AddField(
            model_name='article',
            name='user',
            field=models.ForeignKey(blank=True, to=settings.AUTH_USER_MODEL, null=True),
        ),
        migrations.AlterUniqueTogether(
            name='articletopic',
            unique_together=set([('topic', 'article')]),
        ),
    ]

最奇怪的是,在收到此错误后,我的应用程序从不工作变为工作!但我怎样才能纠正这个问题,以便我可以再次运行迁移?谢谢

0 个答案:

没有答案