API Project: AttributeError: 'list' object has no attribute 'id'

API Project: AttributeError: 'list' object has no attribute 'id'

这是我第一次使用 Python 和 API。我正在尝试根据作者姓名获取书籍列表。我正在为此使用 SQLAlchemy 和 Python 3.10.2。我认为这是所有相关代码:

class Author(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100))
    biography = db.Column(db.String(100))
    publisher = db.Column(db.String(50))

    def __init__(self,name,biography,publisher):
        self.name = name
        self.biography = biography
        self.publisher = publisher

# FUNCTION TO RETURN AN AUTHOR DICTIONARY
def author_dict(new_author):
    author = {
        "id": new_author.id,
        "name": new_author.name,
        "biography": new_author.biography,
        "publisher": new_author.publisher
    }
    return author

# GET A LIST OF BOOKS BASED ON AUTHOR
@app.route('/bookauthor/<name>', methods = ['GET'])
def book_author(name):
    author = Author.query.filter_by(name=name).all()
    authorFilter = author_dict(author)
    return json.dumps(authorFilter)

为什么我会收到此错误:

AttributeError: 'list' object has no attribute 'id'

我该如何解决?

all() 方法将为您 return 您提供 Author 个实例的列表。

您不能通过传递 Author 个实例的列表来调用 author_dict。此函数仅接受一个 Author 实例。但是你可以通过简单的列表理解来实现你正在寻找的东西

@app.route('/bookauthor/<name>', methods = ['GET'])
def book_author(name):
    authors = Author.query.filter_by(name=name).all()
    authorFilter = [author_dict(author) for author in authors]
    return json.dumps(authorFilter)

另一种“更干净”的方法是在 Author class 级别创建一个 to_dict 方法:

class Author(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100))
    biography = db.Column(db.String(100))
    publisher = db.Column(db.String(50))

    def __init__(self,name,biography,publisher):
        self.name = name
        self.biography = biography
        self.publisher = publisher
   
    def to_dict():
        return {
        "id": new_author.id,
        "name": new_author.name,
        "biography": new_author.biography,
        "publisher": new_author.publisher
        }


# GET A LIST OF BOOKS BASED ON AUTHOR
@app.route('/bookauthor/<name>', methods = ['GET'])
def book_author(name):
    authors = Author.query.filter_by(name=name).all()
    return json.dumps([author.to_dict() for author in authors])