【问题标题】:one-to-many append attribute error一对多附加属性错误
【发布时间】:2015-02-11 03:14:07
【问题描述】:

对 SQLAlchemy(和 Python,虽然不那么重要)有点菜鸟。

似乎无法理顺我的帖子和图片模型之间的关系。 Post 对象应该有一个名为“gallery”的列表,一个相关图片对象的列表。还有一个帖子“封面”,一张被选为画廊封面的个人图片。我也在尝试使用 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'))

【问题讨论】:

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


    【解决方案1】:

    您错误地配置了关系。您的picture_ids 列不适用于一对多关系,因为您只能在该列中存储一个picture_id。所以删除该列并使用它来设置画廊:

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

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

    【讨论】:

    • 仍然抛出同样的错误。 uselist 不是用来建立一对一的关系吗?我需要gallery 成为与帖子相关的图片列表。
    • uselist=False 设置在 backref 上,因为每张图片只属于一个帖子。您是否尝试删除其他 kwarg,例如 collection_classorder_byforeign_keys,看看是哪一个导致了问题?
    • 感谢您抽出宝贵时间查看此内容。我删除了picture_ids 并使用了你的gallery 版本,所以没有你建议的其他kwargs,仍然是同样的错误。除非您打算将您的 gallery 版本添加到图片模型中?
    • 虽然您的解决方案不起作用,但我接受了您的回答,因为您发现了问题。谢谢!
    猜你喜欢
    • 2015-12-27
    • 1970-01-01
    • 2011-12-20
    • 2012-03-01
    • 1970-01-01
    • 2023-03-19
    • 2016-05-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多