为什么django错误"列posts_post.category_id不存在"继续回来?

时间:2018-04-05 15:16:30

标签: django django-models

我有一个django博客项目,其中包含以下核心模型:

  

Models.py

class Category(models.Model):

    parentCategoryName = models.ForeignKey('self', blank=True, 
         null=True)
    parentCatSlug = models.SlugField(null=True, blank=True)
    categoryName = models.CharField(max_length=200, null=True)
    categorySlug = models.SlugField(null=True, blank=True)


    def __str__(self):

        full_path = [self.categoryName]               
        k = self.parentCategoryName                          

        while k is not None:
            full_path.append(k.categoryName)
        k = k.parentCategoryName

        return ' -> '.join(full_path[::-1])

    class Meta:
        verbose_name_plural = "categories"

    def save(self, *args, **kwargs):
         self.categorySlug = slugify(self.categoryName)
         self.parentCatSlug = slugify(self.parentCategoryName)
         super(Category, self).save(*args, **kwargs)


class Post(models.Model):

    title = models.CharField(max_length=200)
    category = models.ForeignKey('Category', null=True, blank=True)
    summary = models.CharField(max_length=500, default=True)
    body = RichTextUploadingField()
    pub_date = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, default=True)
    titleSlug = models.SlugField(blank=True)
    authorSlug = models.SlugField(blank=True)
    editedimage = ProcessedImageField(upload_to="primary_images", 
        null=True,
                            processors = [Transpose()],
                            format="JPEG")
   show_in_posts = models.BooleanField(default=True)


    def save(self, *args, **kwargs):
        self.titleSlug = slugify(self.title)
        self.authorSlug = slugify(self.author)
        super(Post, self).save(*args, **kwargs)

    def __str__(self):
        return self.title

当我运行makemigrations并进行迁移时,一切都工作正常,但过了一会儿,我得到上面的错误。我之前已经发布了一个问题,解决方案是删除数据库并重新创建它。这仍然有效,但它经常发生,所以我不得不放弃并重新创建。任何人都可以帮助解释为什么这似乎偶尔会发生吗?

  

回溯

File "/Users/davidmellor/anaconda/envs/py3/lib/python3.6/site-packages/django/db/backends/utils.py" in execute
  65.                 return self.cursor.execute(sql, params)

The above exception (column posts_post.category_id does not exist
LINE 1: SELECT "posts_post"."id", "posts_post"."title", "posts_post"...
                                                        ^
) was the direct cause of the following exception:

File "/Users/davidmellor/anaconda/envs/py3/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
  41.             response = get_response(request)

File "/Users/davidmellor/anaconda/envs/py3/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "/Users/davidmellor/anaconda/envs/py3/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/Users/davidmellor/code/nomadpad/posts/views.py" in getPosts
  27.     return render(request, 'posts/getPosts.html', context)

File "/Users/davidmellor/anaconda/envs/py3/lib/python3.6/site-packages/django/shortcuts.py" in render
  30.     content = loader.render_to_string(template_name, context, request, using=using)

File "/Users/davidmellor/anaconda/envs/py3/lib/python3.6/site-packages/django/template/loader.py" in render_to_string
  68.     return template.render(context, request)

File "/Users/davidmellor/anaconda/envs/py3/lib/python3.6/site-packages/django/template/backends/django.py" in render
  66.             return self.template.render(context)

File "/Users/davidmellor/anaconda/envs/py3/lib/python3.6/site-packages/django/template/base.py" in render
  207.                     return self._render(context)

File "/Users/davidmellor/anaconda/envs/py3/lib/python3.6/site-packages/django/template/base.py" in _render
  199.         return self.nodelist.render(context)

File "/Users/davidmellor/anaconda/envs/py3/lib/python3.6/site-packages/django/template/base.py" in render
  990.                 bit = node.render_annotated(context)

File "/Users/davidmellor/anaconda/envs/py3/lib/python3.6/site-packages/django/template/base.py" in render_annotated
  957.             return self.render(context)

File "/Users/davidmellor/anaconda/envs/py3/lib/python3.6/site-packages/django/template/loader_tags.py" in render
  177.             return compiled_parent._render(context)

File "/Users/davidmellor/anaconda/envs/py3/lib/python3.6/site-packages/django/template/base.py" in _render
  199.         return self.nodelist.render(context)

File "/Users/davidmellor/anaconda/envs/py3/lib/python3.6/site-packages/django/template/base.py" in render
  990.                 bit = node.render_annotated(context)

File "/Users/davidmellor/anaconda/envs/py3/lib/python3.6/site-packages/django/template/base.py" in render_annotated
  957.             return self.render(context)

File "/Users/davidmellor/anaconda/envs/py3/lib/python3.6/site-packages/django/template/loader_tags.py" in render
  72.                 result = block.nodelist.render(context)

File "/Users/davidmellor/anaconda/envs/py3/lib/python3.6/site-packages/django/template/base.py" in render
  990.                 bit = node.render_annotated(context)

File "/Users/davidmellor/anaconda/envs/py3/lib/python3.6/site-packages/django/template/base.py" in render_annotated
  957.             return self.render(context)

File "/Users/davidmellor/anaconda/envs/py3/lib/python3.6/site-packages/django/template/defaulttags.py" in render
  321.             if match:

File "/Users/davidmellor/anaconda/envs/py3/lib/python3.6/site-packages/django/db/models/query.py" in __bool__
  254.         self._fetch_all()

File "/Users/davidmellor/anaconda/envs/py3/lib/python3.6/site-packages/django/db/models/query.py" in _fetch_all
  1118.             self._result_cache = list(self._iterable_class(self))

File "/Users/davidmellor/anaconda/envs/py3/lib/python3.6/site-packages/django/db/models/query.py" in __iter__
  53.         results = compiler.execute_sql(chunked_fetch=self.chunked_fetch)

File "/Users/davidmellor/anaconda/envs/py3/lib/python3.6/site-packages/django/db/models/sql/compiler.py" in execute_sql
  894.             raise original_exception

File "/Users/davidmellor/anaconda/envs/py3/lib/python3.6/site-packages/django/db/models/sql/compiler.py" in execute_sql
  884.             cursor.execute(sql, params)

File "/Users/davidmellor/anaconda/envs/py3/lib/python3.6/site-packages/django/db/backends/utils.py" in execute
  80.             return super(CursorDebugWrapper, self).execute(sql, params)

File "/Users/davidmellor/anaconda/envs/py3/lib/python3.6/site-packages/django/db/backends/utils.py" in execute
  65.                 return self.cursor.execute(sql, params)

File "/Users/davidmellor/anaconda/envs/py3/lib/python3.6/site-packages/django/db/utils.py" in __exit__
  94.                 six.reraise(dj_exc_type, dj_exc_value, traceback)

File "/Users/davidmellor/anaconda/envs/py3/lib/python3.6/site-packages/django/utils/six.py" in reraise
  685.             raise value.with_traceback(tb)

File "/Users/davidmellor/anaconda/envs/py3/lib/python3.6/site-packages/django/db/backends/utils.py" in execute
  65.                 return self.cursor.execute(sql, params)

Exception Type: ProgrammingError at /
Exception Value: column posts_post.category_id does not exist
LINE 1: SELECT "posts_post"."id", "posts_post"."title", "posts_post"...
                                                        ^
  

迁移

from __future__ import unicode_literals

import ckeditor_uploader.fields
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import imagekit.models.fields


class Migration(migrations.Migration):

initial = True

dependencies = [
    migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]

operations = [
    migrations.CreateModel(
        name='Category',
        fields=[
            ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
            ('parentCatSlug', models.SlugField(blank=True, null=True)),
            ('categoryName', models.CharField(max_length=200, null=True)),
            ('categorySlug', models.SlugField(blank=True, null=True)),
            ('parentCategoryName', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='posts.Category')),
        ],
        options={
            'verbose_name_plural': 'categories',
        },
    ),
    migrations.CreateModel(
        name='Comment',
        fields=[
            ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
            ('title', models.CharField(max_length=200)),
            ('pub_date', models.DateTimeField(default=django.utils.timezone.now)),
            ('body', models.CharField(max_length=200)),
            ('approved_comment', models.BooleanField(default=True)),
            ('author', models.ForeignKey(default=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
        ],
    ),
    migrations.CreateModel(
        name='Post',
        fields=[
            ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
            ('title', models.CharField(max_length=200)),
            ('summary', models.CharField(default=True, max_length=500)),
            ('body', ckeditor_uploader.fields.RichTextUploadingField()),
            ('pub_date', models.DateTimeField(default=django.utils.timezone.now)),
            ('titleSlug', models.SlugField(blank=True)),
            ('authorSlug', models.SlugField(blank=True)),
            ('editedimage', imagekit.models.fields.ProcessedImageField(null=True, upload_to='primary_images')),
            ('show_in_posts', models.BooleanField(default=True)),
            ('author', models.ForeignKey(default=True, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
            ('category', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='posts.Category')),
        ],
    ),
    migrations.CreateModel(
        name='Profile',
        fields=[
            ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
            ('bio', models.TextField(blank=True, max_length=500)),
            ('location', models.CharField(blank=True, max_length=30)),
            ('birth_date', models.DateField(blank=True, null=True)),
            ('slug', models.SlugField(default='', unique=True)),
            ('profile_picture', models.ImageField(blank=True, upload_to='profile_images')),
            ('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
        ],
    ),
    migrations.AddField(
        model_name='comment',
        name='post',
        field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='posts.Post'),
    ),
]

2 个答案:

答案 0 :(得分:1)

当我删除我的迁移文件时,我进入了我的mac的文件结构,并清除了所有pycache文件,这些文件不会显示在我的文本编辑器中。虽然我对原因的理解不清楚,但这很有效。

答案 1 :(得分:0)

嗯,从我所看到的情况来看,它看起来不像你的Post模型有category_id字段。我必须看到更多的代码才能理解为什么有一个SQL查询试图在该字段上进行选择。

您是否可以共享产生错误的数据库调用?