Python 数据库模型没有属性

Python 数据库模型没有属性,python,flask,flask-sqlalchemy,Python,Flask,Flask Sqlalchemy,这是一个多对多的数据库,使用Flask_sqlalchemy。我相信我已经准确地遵循了这些示例,但是当运行此操作时,我得到了AttributeError:“Song”对象没有属性“category”,我无法找出问题所在 我怎样才能解决这个问题 association_table = db.Table('association', db.Column('songs_id', db.Integer,

这是一个多对多的数据库,使用Flask_sqlalchemy。我相信我已经准确地遵循了这些示例,但是当运行此操作时,我得到了
AttributeError:“Song”对象没有属性“category”
,我无法找出问题所在

我怎样才能解决这个问题

association_table = db.Table('association',
                             db.Column('songs_id', db.Integer,
                                       db.ForeignKey('songs.id')),
                             db.Column('genres_id', db.Integer,
                                       db.ForeignKey('genres.id'))
                             )

class Song(db.Model):
    __tablename__ = 'songs'
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(80), index=True, unique=True, nullable=False)
    artist = db.Column(db.String(30), primary_key=False,
                       unique=False, nullable=False)
    added = db.Column(db.Date, nullable=False)
    genres = db.relationship("Genre", secondary=association_table, backref=db.backref('songs'))

    def __repr__(self):
        return '{}'.format(self.title)

class Genre(db.Model):
    __tablename__ = 'genres'
    id = db.Column(db.Integer, primary_key=True)
    category = db.Column(db.String(80), index=True,
                         unique=True, nullable=False)
我的插入内容如下所示:

    song = Song(title="test title", artist="test name")
    genre = Genre(category="test category")
    song.category.append(genre)
    db.session.add(song)
    db.session.commit()
编辑: 我在查询方面也有问题

test = Genre.query.filter(Genre.songs.any(title="that song")).all()
print(test)

打印
[,]
而不是打印类型。这是为什么?

您的
歌曲
类没有类别名称属性,但您正试图将您的流派附加到该类别中。 你是有意这么做的吗

song = Song(title="test title", artist="test name")
genre = Genre(category="test category")
song.genres.append(genre)   # You wrote category, but your class only has a "genres" relationship
db.session.add(song)
db.session.commit()

是的,这解决了我的一个问题。我又添加了一个问题,因为它仍然是相同的代码,我认为这比创建新页面容易。@user15705608因为这些是不同的问题,您的编辑没有提供原始问题的详细信息,因此应该是一个“新”问题。否则,当答案与不同的问题相关时,新答案可能会让未来的访问者感到困惑。好的一点,我会在以后的问题中记住这一点。您正在打印类实例的查询集,因此您可以使用[GREEP.CATEGORE for GREEN in test]访问您的流派名称或者像处理song类一样为体裁类提供repr函数。这是一个很小的更正,但现在可以使用了,谢谢