我希望能够创建一篇博客文章,在创建时给它分配一些标签,并将文章和相关标签保存到数据库中。我一直收到这个错误。
TypeError: 不兼容的集合类型。标签不是列表类型...
谁能帮我修改一下我的代码,以实现上述目的?
代码。
postTags = db.Table("postTags", db.Column("postId", db.Integer, db.ForeignKey("posts.id"), primary_key=True), db.Column("tagId", db.Integer, db.ForeignKey("tags.id"), primary_key=True)) # table defining many-to-many between Post and Tag models and tag
class Blogposting(FlaskForm): form to create the post
author = StringField("Author", [DataRequired()])
title = StringField("Title", [DataRequired()])
body = TextAreaField("Body", [DataRequired()])
published = BooleanField(default = False)
postingTags = SelectMultipleField("Posting Tags", coerce=int) #field with the issue
save = SubmitField("Save")
class Post(db.Model): #db model to create post from form data
__tablename__ = "posts"
id = db.Column(db.Integer, primary_key = True)
author = db.Column(db.String(20), nullable=False)
title = db.Column(db.String(60), nullable=False)
postingDate = db.Column(db.DateTime, index=True,
default=datetime.utcnow)
body = db.Column(db.Text, nullable=False)
tags = db.relationship("Tag", secondary=postTags,
backref=db.backref("postTag", lazy="dynamic")) # many to many relationship between Post and Tag
class Tag(db.Model):
__tablename__ = "tags"
id = db.Column(db.Integer, primary_key = True)
tagName = db.Column(db.String(20), unique=True, nullable=False)
posts = db.relationship("Post", secondary=postTags, backref=db.backref("postTag", lazy="dynamic")) # many to many
@app.route("/posts", methods =["GET", "POST"])
def posts():
blogPostForm = Blogposting()
blogPostForm.postingTags.choices = [(i.id, i.tagName) for i in db.session.query(Tag).order_by(Tag.tagName).all()] #dynamic assignment of values to the choices attribute of the SelectMuultipleField
if blogPostForm.validate_on_submit():
postTag = request.form.getlist(id) # grabbring selected values from selectMultipleField before posting to database
blogpostEntries = Post(author = blogPostForm.author.data, title =blogPostForm.title.data, body = blogPostForm.body.data, tags= Tag(id=blogPostForm.postingTags.data)) # save the created post to the db with associated tags from the SelectMultipleField
db.session.add(blogpostEntries)
db.session.commit()
return redirect(url_for("blogEntries"))
return render_template("posts.html", year=copyRightYear, subtitle="Blog Posts", form=blogPostForm)
当在 "一方 "创建关系时,你需要传递一个对象列表到关系属性(tags
),或者直接使用append (tags.append()
)这样的方法。
blogpostEntries = Post(author=blogPostForm.author.data, title =blogPostForm.title.data, body=blogPostForm.body.data)
for tag_id in blogPostForm.postingTags.data:
blogpostEntries.tags.append(Tag.query.get(tag_id))