table items_item没有名为category_id的列

时间:2015-10-01 08:34:40

标签: python django

创建项目时出现此错误,但我可以在category_id看到sqlall

table items_item has no column named category_id

迁移命令:

$ python manage.py makemigrations items
No changes detected

$ python manage.py migrate
Running migrations:
  No migrations to apply.

model.py

from django.db import models

class Category(models.Model):
    name = models.CharField(max_length=200)

# Create your models here.
class Item(models.Model):
    name = models.CharField(max_length=200)
    description = models.TextField(null=True, blank=True)
    image = models.ImageField(upload_to="item_images")
    category = models.ForeignKey(Category)

    show_in_front_page= models.BooleanField(default=True)
    always_show_in_front_page= models.BooleanField(default=True)
    is_trending=models.BooleanField(default=True)

sqlall

# $ python manage.py sqlall items
BEGIN;
CREATE TABLE "items_category" (
    "id" integer NOT NULL PRIMARY KEY AUTOINCREMENT,
    "name" varchar(200) NOT NULL
)
;
CREATE TABLE "items_item" (
    "id" integer NOT NULL PRIMARY KEY AUTOINCREMENT,
    "name" varchar(200) NOT NULL,
    "description" text,
    "image" varchar(100) NOT NULL,
    "category_id" integer NOT NULL REFERENCES "items_category" ("id"),
    "show_in_front_page" bool NOT NULL,
    "always_show_in_front_page" bool NOT NULL,
    "is_trending" bool NOT NULL
)
;
CREATE INDEX "items_item_6f33f001" ON "items_item" ("category_id");

COMMIT;

admin.py

from django.contrib import admin

# Register your models here.
from .models import Item, Category


admin.site.register(Item)
admin.site.register(Category)

1 个答案:

答案 0 :(得分:3)

如果category_id列已在应用的迁移文件中,但尚未在数据库中创建,则最简单的修复方法是手动添加列。从上面的sqlall输出中可以很容易地计算出SQL。

./manage.py dbshell # open a db shell

# Add the column
ALTER TABLE items_item ADD COLUMN "category_id" integer NOT NULL REFERENCES "items_category" ("id");
# Add the index
CREATE INDEX "items_item_6f33f001" ON "items_item" ("category_id");