Article
和Image
具有多对多关系,其中间表为ArticleImage
。我希望我会在Article
表中看到1行,在Image
表中看到3行,在ArticleImage
表中看到3行。 Article
和ArticleImage
部分按预期工作,但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,我做了一些小改动)
答案 0 :(得分:1)
根据您引用的article,您还应在ArticleImage
中添加构造函数,以便在创建ArticleImage
对象时将Image
与ArticleImage
相关联,否则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
代码。