繁体   English   中英

多对多关系 SQL 炼金术

[英]Many To Many Relation SQL Alchemy

我想使用 Flask-SQLALchemy 在(书)和(作者)之间建立多对多关系。

class book(db.Model):
__tablename__ = "book"
isbn_code = db.Column(db.String(10), primary_key=True) #
book_title = db.Column(db.String(70))
book_language = db.Column(db.String(20))
no_of_copies = db.Column(db.Integer)
is_Available = db.Column(db.String(1))
publication_year = db.Column(db.Integer)
bookItem = db.relationship('book_item' , backref= 'book')
book_reserved = db.relationship('book_reserve', backref= 'bookreserv')


book_autho = db.Table('book_autho' , 
 db.Column('isbn_code' ,db.String(10) , db.ForeignKey('book.isbn_code')) ,
 db.Column('author_id' ,db.Integer , db.ForeignKey('author.author_id'))) 


class author(db.Model): 
 author_id = db.Column(db.Integer , primary_key = True)
 name = db.Column(db.String(30))
 DOB = db.Column(db.DateTime)
 authors = db.relationship('book', secondary = book_autho ,backref = db.backref('book_author' , lazy = 'dynamic'))



    test = author.query.filter_by(name='Lucas').first()
    print (test.book_author)
    for books in test.book_author :
        print(books.isbn_code)

但是,我面临这个错误:

Traceback (most recent call last):
  File "models.py", line 121, in <module>
    print (test.book_author)
AttributeError: 'author' object has no attribute 'book_author'

谢谢你..

您与 book_author 的关系位于 authors 属性上,因此您可以使用test.authors访问它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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