从模型对象查询时的问题

0 投票
2 回答
1181 浏览
提问于 2025-04-16 11:21

我正在尝试用Pylons和SqlAlchemy(通过Elixir)一起工作。

这是我的测试数据库的模型文件,路径是testdb/model/entities.py:

from elixir import *

metadata.bind = "mysql://testdb:hundertwasser@localhost/testdb"
metadata.bind.echo = True

class Post(Entity):
    text = Field(Unicode(128))

这是控制器的代码:

import logging

from pylons import request, response, session, tmpl_context as c, url
from pylons.controllers.util import abort, redirect

from testdb.lib.base import BaseController, render

log = logging.getLogger(__name__)

from testdb.model.entities import *

class MainController(BaseController):

    def index(self):
        c.posts = Post.query.all()
        print "Test"
        return render('/index.mako')

    def submit(self):
        post = Post()
        post.text = request.POST.get['text']
        session.commit()

当我运行这个应用程序时,出现了一个错误,内容是:

AttributeError: type object 'Post' has no attribute 'query'

有人知道我哪里出错了吗?

2 个回答

0

我对Elixir不太了解,但把下面的内容放在.ini文件里不就够了吗?

sqlalchemy.url = mysql://user:pass@localhost/dbname?charset=utf8&use_unicode=0
sqlalchemy.pool_recycle = 3600

?后面的所有内容都是为了避免编码问题。第二行的设置是为了防止MySQL关闭不活跃的连接(实际上它每小时会重新连接一次)。

1

答案如下:

在entities.py文件的底部缺少以下两行代码:

setup_all()
create_all()

撰写回答