Flask SQLAlchemy AttributeError:'NoneType'对象没有属性'append'

时间:2018-08-20 21:22:09

标签: python flask-sqlalchemy

我已经在login成功创建了一个用户,现在我正在查询它:

user = User.query.filter_by(restaurant=session['user']).first()

user打印:

<ID 1>, <User u'Big Burger'>, <Username u'me'>, <Email me@mac.com'>

在这一点上,我正在尝试将append对象创建并user,像这样:

burger = Menu('cheeseburger')

db.session.add(burger)
db.session.commit()

user.menu.append(burger)

我得到:

  

AttributeError:'NoneType'对象没有属性'append'

但是如果打印NoneType,它将如何获得burger的回溯:

<Items u'cheeseburger'>

models.py

class User(db.Model):
    __tablename__='user'
    """
    Model for storing user data. 
    """
    id = db.Column(db.Integer, primary_key=True)
    restaurant = db.Column(db.String(50))
    username = db.Column(db.String(80), unique=True)
    email = db.Column(db.String(120), unique=True)

    menu = db.relationship("Menu",
                    backref=db.backref('user'), uselist=False)


    def __init__(self, restaurant, username, email):
        self.restaurant = restaurant
        self.username = username
        self.email = email


    def __repr__(self):
        return '<ID %r>, <User %r>, <Username %r>, <Email %r>' % (self.id,                                                                      self.restaurant,                                                                      self.username,                                                                      self.email)

    @property
    def serialize(self):
       """Return object data in easily serializeable format"""
       return { 'id' : self.id,
                'mail' : self.email,
                'restaurant' : self.restaurant,
                'username' : self.username,
                'menu' : self.menu }

class Menu(db.Model):
    __tablename__='menu'
    """
    Model for storing menus. 
    """

    id = db.Column(db.Integer, primary_key=True)
    items = db.Column(db.String(50))    
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))

    def __init__(self, items):
        self.items = items


    def __repr__(self):
        return '<items %r>' % (self.items)

    @property
    def serialize(self):
       """Return object data in easily serializeable format"""
       return { 'items' : self.items }

1 个答案:

答案 0 :(得分:0)

是user.menu,它没有append属性,而不是burger。将Uselist切换为True将帮助您:

.wrapper{
  width: 100%;
  max-width: 1200px; //set your `max-width` here
  max-height: auto; //necessary to keep proportion
  margin: 0 auto; //centering 

}
.videoWrapper{
  width:100%;
  position: relative;
  padding-top: 56.25%;
  overflow: hidden;
}

iframe{
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  border: 0;
}

<div class="wrapper">
        <div class="videoWrapper">
          <iframe src=""></iframe>
        </div>
</div>

现在的汉堡应该有您想要的东西。