一对多追加属性错误

时间:2015-02-11 03:14:07

标签: python-3.x flask sqlalchemy flask-sqlalchemy

使用SQLAlchemy的一个菜鸟(和Python,但不那么)。

似乎无法理顺我的Post和Picture模型之间的关系。 帖子对象应该有一个名为' gallery'的列表,一个相关图片对象的列表。还有一个Post'封面,一个单独的图片被选为画廊封面。我还尝试使用OrderingList来维护图库中的图片顺序。

在我的视图中尝试将图片附加到post.gallery时,会抛出以下内容:

AttributeError: 'NoneType' object has no attribute 'append'

以下是模型:

class Post(db.Model):
    __tablename__ = 'posts'
    id = db.Column(db.Integer, primary_key=True)
    cover_id = db.Column(db.Integer, db.ForeignKey('pictures.id',
            use_alter=True, name='fk_post_cover_id'))
    picture_ids = db.Column(db.Integer, db.ForeignKey('pictures.id',
            use_alter=True, name='fk_post_picture_ids'))
    cover = db.relationship('Picture', foreign_keys=cover_id, post_update=True)
    gallery = db.relationship('Picture', foreign_keys=picture_ids,
            order_by='Picture.position',
            collection_class=ordering_list('position'))

class Picture(db.Model):
    __tablename__ = 'pictures'
    id = db.Column(db.Integer, primary_key=True)
    position = db.Column(db.Integer)
    post_id = db.Column(db.Integer, db.ForeignKey('posts.id'))

我猜测它是我配置两个模型之间的多重关系的方式。帮我看看我错过了什么!

编辑:根据badAPI的建议,picture_ids将只包含一个值,而不包含值列表。我的模型的以下更改产生了一对多的工作关系:

class Post(db.Model):
__tablename__ = 'posts'
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
    cover_id = db.Column(db.Integer, db.ForeignKey('pictures.id',
            use_alter=True, name='fk_post_cover_id'))
    cover = db.relationship('Picture', uselist=False, foreign_keys=cover_id,
            post_update=True)

class Picture(db.Model):
    __tablename__ = 'pictures'
    id = db.Column(db.Integer, primary_key=True)
    position = db.Column(db.Integer)
    post_id = db.Column(db.Integer, db.ForeignKey('posts.id'))

    gallery = db.relationship('Post', foreign_keys=post_id,
            order_by='Picture.position',
            collection_class=ordering_list(position),
            backref=db.backref('gallery'))

1 个答案:

答案 0 :(得分:0)

您错误地配置了关系。您的picture_ids列不适用于一对多关系,因为您只能在该列中存储一个picture_id。因此,请删除该列并使用此列设置图库:

gallery = db.relationship('Picture', backref=db.backref('post', uselist=False))

然后,您可以从post_id课程中删除Picture列,并使用Picture.post访问所有帖子。