我正在尝试将行从一个DB实例复制到另一个DB实例,在不同的环境中使用相同的模式。此架构中的两个表的链接方式使它们产生相互依赖的行。插入这些行后,post_update
将按预期运行,但是update语句将ID字段的值设置为None
,而不是预期的ID
只有在使用已从会话中删除的对象时才会发生这种情况。使用新创建的对象时,post_update
的行为与预期完全相同。你知道吗
示例
我的关系是这样的:
class Category(Base):
__tablename__ = 'categories'
id = Column(Integer, primary_key=True)
top_product_id = Column(Integer, ForeignKey('products.id'))
products = relationship('Product', primaryjoin='Product.category_id == Category.id', back_populates='category', cascade='all', lazy='selectin')
top_product = relationship('Product', primaryjoin='Category.top_product_id == Product.id', post_update=True, cascade='all', lazy='selectin')
class Product(Base):
__tablename__ = 'products'
id = Column(Integer, primary_key=True)
category_id = Column(Integer, ForeignKey('categories.id'))
category = relationship('Category', primaryjoin='Product.category_id == Category.id', back_populates='products', cascade='all', lazy='selectin')
如果我从一个数据库中查询一个类别及其相关产品并尝试将它们写入另一个数据库,则top_product_id
的更新不会按预期进行,而是将值设置为None
。以下代码:
category = source_session.query(Category).filter(Category.id == 99).one()
source_session.expunge(category)
make_transient(category)
for products in category.products:
make_transient(product)
# this step is necessary to prevent a foreign key error on the initial category insert
category.top_product_id = None
dest_session.add(category)
导致SQLAlchemy生成以下SQL:
INSERT INTO categories (name, top_product_id) VALUES (%s, %s)
('SomeCategoryName', None)
INSERT INTO products (name, category_id) VALUES (%s, %s)
('SomeProductName', 99)
UPDATE categories SET top_product_id=%s WHERE categories.id = %s
(None, 99)
但是如果我使用新创建的对象,一切都会正常工作。你知道吗
category = Category()
product = Product()
category.name = 'SomeCategoryName'
product.name = 'SomeProductName'
product.category = category
category.top_product = product
dest_session.add(category)
结果:
INSERT INTO categories (name, top_product_id) VALUES (%s, %s)
('SomeCategoryName', None)
INSERT INTO products (name, category_id) VALUES (%s, %s)
('SomeProductName', 99)
UPDATE categories SET top_product_id=%s WHERE categories.id = %s
(1, 99)
除了这个区别之外,这两个动作之间的行为都是一样的。所有其他关系都已正确创建,ID和外键按预期设置。只有在由post_update
创建的update子句中设置的top_product_id
无法按预期的方式工作。你知道吗
作为额外的故障排除步骤,我尝试了:
在第一次刷新DB时,正确设置top_product_id
。第二,它被设置为None
。因此,这证实了问题不在于会话中的差异,而是与从会话中删除对象并使其成为临时对象有关。在“删除/生成”瞬态过程中,必须有某种事情发生/不发生,使这些对象处于一种根本不同的状态,并阻止post_update
以应有的方式运行。你知道吗
如果您有任何想法,我们将不胜感激。你知道吗
我假设你的
Base
类混合在name
列中?你知道吗您的目标是使
inspect(category).committed_state
看起来与新创建的对象类似(除了id
属性)。每个产品对象都一样。你知道吗在“新创建的对象”示例中,
category
的committed_state
在刷新会话之前如下所示:而
product
的committed_state
看起来是这样的:要获得更新后的行为,您需要同时终止
category.top_product_id
(以防止它包含在INSERT
)和伪造category.top_product
的committed_state
(以使SQLAlchemy相信值已更改,因此需要引起UPDATE
)。你知道吗首先,在使
category
变为瞬态之前使category.top_product_id
过期:然后是fudge
category.top_product
的committed_state
(这可能发生在category
瞬态之前或之后):完整示例:
它在
dest_session
中生成这个DML:似乎
make_transient
应该将committed_state
重置为一个新对象,但我猜不是。你知道吗相关问题 更多 >
编程相关推荐