如何在Flask视图中使用多对多字段?

时间:2016-01-16 15:44:55

标签: python orm flask sqlalchemy flask-sqlalchemy

我正在尝试使用Flask创建博客。每个帖子都可以有多个标签,每个标签也可以与多个帖子相关联。所以我创建了一个多对多的关系。我的问题是如何在创建新帖子时保存多个标签。并且由于每个帖子可以有不同数量的标签,我如何在表格中显示?另外,如何与帖子一起创建新标签,然后将这些标签与其他帖子一起使用? 这是models.py -

postcategory = db.Table('tags',
    db.Column('posts_id', db.Integer, db.ForeignKey('posts.id')),
    db.Column('categories_id', db.Integer, db.ForeignKey('categories.id'))
)

class Post(db.Model):
    __tablename__ = 'posts'
    id = db.Column(db.Integer, primary_key=True)     
    title = db.Column(db.String)
    content = db.Column(db.Text)
    slug = db.Column(db.String, unique=True)
    published = db.Column(db.Boolean, index=True)
    timestamp = db.Column(db.DateTime, index=True)
    categories = db.relationship('Category', secondary=postcategory, backref='posts' )

    def __init__(self, title, content):
        self.title = title
        self.content = content

class Category(db.Model):
    __tablename__ = 'categories'
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String, index=True)

这是我正在研究的观点 -

def create_article():
    if request.method == 'POST':
        if request.form.get('title') and request.form.get('content') and request.form.get('slug') and request.form.get('published'):
            post = Post(request.form['title'], request.form['content'], request.form['slug'], request.form['published'])

我确信有一个简单的解决方案,我只是让这复杂化,但我是网络开发的新手,所以请帮忙。

1 个答案:

答案 0 :(得分:0)

您可以使用getlist从表单中提取类别,并将它们添加到Post对象中。如果您有以下复选框:

<form>
    <input type="checkbox" name="categories" value="foo">
    <input type="checkbox" name="categories" value="bar" checked>
</form>

在您的查看方法中,您可以执行以下操作:

categories_from_form = request.form.getlist('categories') # ['bar']
# create Category objects with the form data
categories = [Category(title=title) for title in categories_from_form]

post = Post(request.form['title'], request.form['content'], request.form['slug'], request.form['published'])
post.categories = categories # attach the Category objects to the post
...