简体   繁体   中英

How do I use Flask-SQLAlchemy with a many to many model?

I want to create a many to many relationship using Flask-SQLAlchemy but am falling down on even the most simple example. I have used the sample code from the link here and added the essentials to get this functional in a file call app.py:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)


    tags = db.Table('tags',
        db.Column('tag_id', db.Integer, db.ForeignKey('tag.id'), primary_key=True),
        db.Column('page_id', db.Integer, db.ForeignKey('page.id'), primary_key=True)
    )

class Page(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    page_name = db.Column(db.String(30))
    tags = db.relationship('Tag', secondary=tags, lazy='subquery',
        backref=db.backref('pages', lazy=True))

class Tag(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    tag_name = db.Column(db.String(30))

I've then in Python command line typed:

from app import * 
db.create_all()

Which has created the file correctly and I can see the three tables. Perfect!

How do I now go about creating the pages and tags in this example... I expected something like:

new_page = Page(tags=["tagone"])

But I get an error:

AttributeError: 'str' object has no attribute '_sa_instance_state

I'm not sure where to start to be honest..

I figured it out with more searching and testing. I am not sure if this is best practice but it works:

 new_page_too = Page(page_name='Johnny New')
 new_tag = Tag(tag_name='Solved')
 new_tag_too = Tag(tag_name='Fixed It!')
 new_page_too.tags.append(new_tag)
 new_page_too.tags.append(new_tag_too)
 db.session.add(new_page_too)
 db.session.commit()

Very pleased and I love SQLAlchemy :-)

Also thanks to a comment you can also do this:

new_page = Page(page_name='Johnny Third', tags=[Tag(tag_name='Tag1Test'), Tag(tag_name='Tag2Test')])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM