无法正确地保持多对多关系

时间:2015-01-15 03:41:01

标签: python sqlalchemy

ArticleImage具有多对多关系,其中间表为ArticleImage。我希望我会在Article表中看到1行,在Image表中看到3行,在ArticleImage表中看到3行。 ArticleArticleImage部分按预期工作,但Image表中有0行,而新{3}表的ArticleImage表中的外键列'image_id'添加的行为“NULL”。我错过了在Image表中正确保留行? (没有打印错误)

我的代码:

db_session = some_function()  # get connection to database here
try:
    article = Article()
    db_session.add(article)
    article.name = 'new post #1'
    article.author = 'pojan'
    article.images.append(Image('img1.jpg'))
    article.images.append(Image('img2.jpg'))
    article.images.append(Image('img3.jpg'))
    db_session.merge(article)
    db_session.commit()

    print db_session.query(Article).count()       # 1
    print db_session.query(ArticleImage).count()  # 3
    print db_session.query(Image).count()         # 0 <- error here, images are not added 

except Exception as e:
    print e

我还尝试了以下代码,现在将Image添加到数据库中,但ArticleImage中的image_id列仍保留为NULL:

    article = Article()
    db_session.add(article)
    article.name = 'new post #1'
    article.author = 'pojan'

    image1 = Image('img1.jpg')
    image2 = Image('img2.jpg')
    image3 = Image('img3.jpg')
    db_session.add(image1)
    db_session.add(image2)
    db_session.add(image3)

    article.images.append(image1)
    article.images.append(image2)
    article.images.append(image3)
    db_session.merge(article)
    db_session.commit()

我的模特:

class Image(EntityClass):
    attributes = ['id', 'name', 'path']

    id = Column(Integer, primary_key=True)
    name = Column(String(255), nullable=False)
    path = Column(String(255), nullable=False, unique=True)

    def __init__(self, name):
        self.name = name
        self.path = '/root/' + name

class ArticleImage(EntityClass):

    article_id = Column(Integer, ForeignKey('article.id'))
    image_id = Column(Integer, ForeignKey('image.id'))
    image = relationship(Image)
    position = Column(Integer)

class Article(EntityClass):

    attributes = ['id','name','author']

    id = Column(Integer, primary_key=True)

    _images = relationship(ArticleImage,
             order_by=[ArticleImage.position],
             collection_class=ordering_list('position'))
    images = association_proxy('_images', 'image')

    name = Column(String(255), nullable=False)
    author = Column(String(255), nullable=False)

(设计基于我在互联网上找到的article,我做了一些小改动)

2 个答案:

答案 0 :(得分:1)

根据您引用的article,您还应在ArticleImage中添加构造函数,以便在创建ArticleImage对象时将ImageArticleImage相关联,否则ArticleImage永远不会知道它应该引用哪个图像行。

class ArticleImage(EntityClass):

    article_id = Column(Integer, ForeignKey('article.id'))
    image_id = Column(Integer, ForeignKey('image.id'))
    image = relationship(Image)
    position = Column(Integer)

    def __init__(self, image=None):
        self.image = image

答案 1 :(得分:0)

与您提供的示例相比,您错过了ArticleImage中的主键。

我会得到

  

sqlalchemy.exc.ArgumentError:Mapper Mapper | ArticleImage | article_image无法为映射表组装任何主键列&#39; article_image&#39;

使用您的ArticleImage代码。