python - Many-to-many db.relationship implementation in saving to database. SQLAlchemy -
Text after "
My app looks:
app = bottle (__name__, template_folder = 'templates ') App.config.from_object (' config ') db = SQLAlchemy (application) Looks like my SQLAlchemy classes:
connection = db .Table ('connection', db.metadata, db.Column ('book_id', db.Integer, db.ForeignKey ('books.id')), db.Column ('author_id', db.Integer, db.ForeignKey ('Authors .id'))) Category Writer (db.Model): __tablename__ = '__searchable___ of the authors = [' a_name '] __table_args__ = {' sqlite_autoincrement ': is 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': is true,}? Id = db.Column (db.Integer, primary_key = true) b_name = db.Column (db.String (80)) authors = db.relationship ('author', secondary = lambda: connection, backf = db.backref (' Books')) D Ef __repr __ (self): Back to Unicode (self. B_name) As you can see, SQLLame classes are many DB structures, what I want, Add book titles and eighteen names to the same html-form and save it in my database.
@ 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')) But some are unavailable here. These newly created books and writers are not correlated with each other. They do not have author-book relations. Which statement do I need to implement this relationship?
You must connect two objects to make the relationship explicitly. For example:
author.books.append (book)
Comments
Post a Comment