Article
和Image
具有多对多关系,并且它们的中间表为ArticleImage
。我希望在Article
表中看到1行,在Image
表中看到3行,在ArticleImage
表中看到3行。 Article
和ArticleImage
部分按预期工作,但是Image
表中有0行,而ArticleImage
表中的foreeigh-key列“ image_id”中,这3个新添加的行为“ 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,并且做了一些小的更改)
最佳答案
根据您引用的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