我得到错误 As TypeError: 'Query' object is not callable
。
我正在 Pyramid 中创建博客引擎,但我被困在 QuerySelectField 中,如何显示在名为 Categories 的单独表中存在的类别,该表是文章模型的 ForeignKey?
预期产出
类别字段应显示数据库中存在的所有类别以供选择。
模型.py
DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
Base = declarative_base()
class Category(Base):
__tablename__ = 'categories'
id = Column(Integer, primary_key=True)
name = Column(String(100), unique=True, nullable=False)
description = Column(Text, nullable=False)
class Article(Base):
__tablename__ = 'articles'
id = Column(Integer, primary_key=True)
title = Column(String(255), unique=True, nullable=False)
body = Column(Text, nullable=False)
category = Column(ForeignKey(Category.name), nullable=False)
created = Column(DateTime, default=datetime.datetime.now)
@property
def slug(self):
return urlify(self.title)
@property
def created_in_words(self):
return time_ago_in_words(Article.created)
视图.py
from pyramid.view import view_config
from pyramid.httpexceptions import HTTPFound
import sqlalchemy as sa
from blog.forms import ArticleCreateForm
from blog.models import (
DBSession,
Article, Category,
)
@view_config(route_name='home', renderer='articles/index.jinja2')
def index(request):
articles = DBSession.query(Article).order_by(sa.desc(Article.created))
return {'articles': articles}
@view_config(route_name='article_action', match_param='action=create', renderer='articles/create.jinja2')
def create(request):
article = Article()
form = ArticleCreateForm(request.POST)
if request.method == 'POST' and form.validate():
form.populate_obj(article)
DBSession.add(article)
return HTTPFound(location=request.route_url('home'))
return {'form':form, 'action':request.matchdict.get('create')}
表格.py
from models import DBSession
from models import Category
from wtforms import Form, TextField, TextAreaField, SubmitField, validators
from wtforms.ext.sqlalchemy.fields import QuerySelectField
def Category_choice():
return DBSession.query(Category.name)
class ArticleCreateForm(Form):
title = TextField('Title', [validators.required(), validators.length(min=1,max=240)])
body = TextAreaField('Content', [validators.required()])
category = QuerySelectField('Category', query_factory=Category_choice())
submit = SubmitField()