以下是主题模型:
class Topic(db.Model):
__tablename__ = 'topics'
topic_id = db.Column(db.Integer, autoincrement=True, primary_key=True)
topic_name = db.Column(db.String(200), unique=True, nullable=False)
posts = db.relationship('Association', back_populates='topic')
以下是Post模型:
class Post(db.Model):
__tablename__ = 'posts'
post_id = db.Column(db.Integer, autoincrement=True, primary_key=True)
title = db.Column(db.String(200), nullable=False)
content = db.Column(db.Text, nullable=False)
timestamp = db.Column(db.DateTime, index=True, default=datetime.utcnow)
likes = db.Column(db.Integer, default=0)
dislikes = db.Column(db.Integer, default=0)
author_id = db.Column(db.Integer, db.ForeignKey('users.user_id'))
author = db.relationship('User', back_populates='posts')
topics = db.relationship('Association', back_populates='post')
以下是关联模型:
class Association(db.Model):
__tablename__ = 'post_topic_assoc'
post_id = db.Column('post_id', db.ForeignKey('posts.post_id'), primary_key=True)
topic_id = db.Column('topic_id', db.ForeignKey('topics.topic_id'), primary_key=True)
post = db.relationship('Post', back_populates='topics')
topic = db.relationship('Topic', back_populates='posts')
这是我的查看功能:
def create(user_id):
form = PostForm()
query = db.session.query(Topic.topic_id, Topic.topic_name)
topics = query.all()
form.topics.choices = topics
if request.method == 'POST' and form.validate_on_submit():
choice_instances = list(map(Topic.query.get, form.topics.data))
new_post = Post(title=form.title.data,
content=form.content.data,
author=current_user)
new_post.topics.extend(choice_instances)
db.session.add(new_post)
db.session.commit()
flash('You post has been created')
return redirect(url_for('blueprint_user.user_home',
user_id=current_user.user_id))
错误仅说明了这一点:
KeyError:“发布”
我的执行确实在new_post.topics.extend(choice_instances)
行停止。
为什么我不能使用.extend()插入主题?我建立多对多关系的方式有什么问题吗?
请click here进行完整的追溯。
我遇到的大多数SO问题(例如this)都是使用关联表方法而非关联模型。即使在那些.append()或.extend()在工作,但在我的代码中却没有。
请指导我,我是SqlAlchemy的初学者。