Question

My app looks like:

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

My SQLAlchemy classes look like:

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)

As you can see. The SQLAlchemy classes are many-to-many db structure. What I need is to add book`s title and ahthors names at the same html-form and save it at 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 something is missing here. These new created book and author do not correlate to each other. They do not have authors-books relationship. What statement I need to add to implement this relationship?

Was it helpful?

Solution

You have to connect the two objects explicitly to create the relationship. For example:

author.books.append(book)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top