0

我正在使用 Python 和 Django 开发一个简单的论坛,但是在为 Post 创建数据库条目时遇到了一个小问题:

(python manage.py shell):
     >>> from forums.models import User,Category,Post

     >>> nu = User(username="daniel", password="test")
     >>> nu.user_ip = "127.0.0.1"
     >>> nu.save()
     >>> User.objects.all()
         [<User: daniel>]

     >>> c = Category(category_name="Default")
     >>> c.save()
     >>> Category.objects.all()
         [<Category: Default>]

     >>> p = Post(post_name="Test", post_content="Hello, world", category=Category.objects.get(pk=1), poster=User.objects.get(pk=1))
     >>> p.save()

“/usr/local/Cellar/python/2.7.3/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py”,第 344 行,在执行返回 Database.Cursor.execute(self, query, params) DatabaseError: table forums_post has no column named category_id

这是我的 models.py 文件:

from django.db import models
from datetime import date

class User(models.Model):
    username = models.CharField(max_length=200, unique=True)
    password = models.CharField(max_length=300)
    creation_date = models.DateField(default=date.today)
    user_ip = models.IPAddressField()

    def __unicode__(self):
        return self.username

class Category(models.Model):
    category_name = models.CharField(max_length=50)

    def __unicode__(self):
        return self.category_name

class Post(models.Model):
    post_name = models.CharField(max_length=150)
    post_content = models.CharField(max_length=500)
    category = models.ForeignKey(Category)
    poster = models.ForeignKey(User)

    def __unicode__(self):
        return self.post_name

为什么要查找“category_id”列?所有帮助表示赞赏。

4

1 回答 1

2

除非您db_column在定义外键时指定 a,否则 Django 将_id在尝试查询数据库时附加到您提供的属性名称。

我猜在您的数据库中,您的专栏被称为category.

您可以将列名更改为category_id或定义您的类别外键,如下所示:

category = models.ForeignKey(Category, db_column='category')
于 2013-02-24T22:25:12.360 回答