2014-04-25 21 views
0

我的應用程序是這樣的:保存到數據庫的多對多db.relationship實現。 SQLAlchemy的

app = Flask(__name__, template_folder='templates') 
app.config.from_object('config') 
db = SQLAlchemy(app) 

我的SQLAlchemy類的樣子:

connections = db.Table('connections', db.metadata, 
    db.Column('book_id', db.Integer, db.ForeignKey('books.id')), 
    db.Column('author_id', db.Integer, db.ForeignKey('authors.id')) 
) 

class Author(db.Model): 
    __tablename__ = 'authors' 
    __searchable__ = ['a_name'] 
    __table_args__ = {'sqlite_autoincrement': True,} 

    id = db.Column(db.Integer, primary_key=True) 
    a_name = db.Column(db.String(80), unique=True) 

    def __repr__(self): 
     return unicode(self.a_name) 


class Book(db.Model): 
    __tablename__ = 'books' 
    __searchable__ = ['b_name'] 
    __table_args__ = {'sqlite_autoincrement': True,} 

    id = db.Column(db.Integer, primary_key=True) 
    b_name = db.Column(db.String(80)) 
    authors = db.relationship('Author', secondary=lambda: connections, 
           backref=db.backref('books')) 

    def __repr__(self): 
     return unicode(self.b_name) 

正如你所看到的。 SQLAlchemy類是多對多數據庫結構。 我需要的是添加書的標題和ahthors名稱在相同的HTML表單,並將其保存在我的數據庫。

@app.route('/add', methods=['GET', 'POST']) 
def add_book(): 
    if request.method == "POST": 
     author = Author(a_name = request.form['author']) 
     book = Book(b_name = request.form['book']) 
     db.session.add(author) 
     db.session.add(book) 
     db.session.commit() 
     return redirect(url_for('show_books')) 

但是在這裏丟失了一些東西。這些新創建的書和作者不相互關聯。他們沒有作者與書籍的關係。 爲了實現這種關係,我需要添加什麼聲明?

回答

1

您必須明確連接兩個對象才能創建關係。例如:

author.books.append(book) 
+0

它幫助,謝謝。這是我需要的正確的代碼字符串。有趣的是,我正在讀你的博客,並從你那裏得到一個消息:) – zds