简体   繁体   English

SQLAlchemy双向关系关联代理

[英]SQLAlchemy Bidirectional Relationship association proxy

Update: 更新:

For anyone having this issue, with the very latest SQLAlchemy this behaviour has been fixed. 对于有此问题的任何人,使用最新的SQLAlchemy,此行为已得到修复。

Original issue: 原始问题:

I am having a problem with getting association proxies to update correctly. 我遇到了使关联代理正确更新的问题。

Using the example models here: http://docs.sqlalchemy.org/en/rel_0_7/orm/extensions/associationproxy.html#simplifying-association-objects 使用此处的示例模型: http//docs.sqlalchemy.org/en/rel_0_7/orm/extensions/associationproxy.html#simplifying-association-objects

But changing UserKeyword with this line: 但是使用以下行更改UserKeyword:

keyword = relationship("Keyword", backref=backref("user_keywords", cascade="all, delete-orphan"))

and adding this to Keyword: 并将其添加到关键字:

users = association_proxy('user_keywords', 'user')

So a keyword instance has a list of users. 因此,关键字实例具有用户列表。

The following works as expected: 以下按预期工作:

>>> rory = User("rory")
>>> session.add(rory)
>>> chicken = Keyword('chicken')
>>> session.add(chicken)
>>> rory.keywords.append(chicken)
>>> chicken.users
[<__main__.User object at 0x1f1c0d0>]
>>> chicken.user_keywords
[<__main__.UserKeyword object at 0x1f1c450>]

But removals do strange things. 但删除做奇怪的事情。 Removing from the association proxy lists like so: 从关联代理列表中删除如下:

>>> rory.keywords.remove(chicken)

Causes an integrity error as SA tries to set one of the foreign key columns to null. SA尝试将其中一个外键列设置为null时,会导致完整性错误。

Doing this: 这样做:

>>> rory.user_keywords.remove(rory.user_keywords[0])

Results in this: 结果如下:

>>> chicken.users
[None]

I have missed something obvious haven't I? 我错过了一些明显没有的东西吗?

UserKeyword requires that it be associated with both a Keyword and User at the same time in order to be persisted. UserKeyword要求它同时与KeywordUser相关联UserKeyword When you associate it with a User and Keyword , but then remove it from the User.user_keywords collection, it's still associated with the Keyword . 当您将其与UserKeyword相关联,但随后将其从User.user_keywords集合中删除时,它仍然与Keyword相关联。

>>> rory.keywords.remove(chicken)

# empty as we expect
>>> rory.user_keywords
[]   

# but the other side, still populated.  UserKeyword 
# has no User, but still has Keyword
>>> chicken.user_keywords
[<__main__.UserKeyword object at 0x101748d10>]

# but the User on that UserKeyword is None
>>> chicken.user_keywords[0].user is None
True

# hence accessing the "association" gives us None
# as well
>>> chicken.users
[None]

So if we were to flush() this right now, you've got a UserKeyword object ready to go but it has no User on it, so you get that NULL error. 因此,如果我们现在要刷新(),你已经准备好了一个UserKeyword对象,但它上面没有User ,所以你得到了NULL错误。 At INSERT time, the object is not considered to be an "orphan" unless it is not associated with any Keyword.user_keywords or User.user_keywords collections. 在INSERT时,该对象不被视为“孤儿”,除非它与任何Keyword.user_keywords User.user_keywords集合User.user_keywords Only if you were to say, del chicken.user_keywords[0] or equivalent, would you see that no INSERT is generated and the UserKeyword object is forgotten. 只有当您说del chicken.user_keywords[0]或等效时,您才会看到没有生成INSERT并且忘记了UserKeyword对象。

If you were to flush the object to the database before removing it from "rory", then things change. 如果您要在将对象从“rory”中删除之前将对象刷新到数据库,那么事情会发生变化。 The UserKeyword is now persistent, and when you remove "chicken" from "rory.keywords", a "delete-orphan" event fires off which does delete the UserKeyword , even though it still is associated with the Keyword object: UserKeyword现在是持久的,而当你从“rory.keywords”,“删除孤儿”事件打完这删除删除“鸡” UserKeyword ,即使它仍然是有关联的Keyword对象:

rory.keywords.append(chicken)

session.flush()

rory.keywords.remove(chicken)

session.flush()

you see the SQL: 你看到SQL了:

INSERT INTO "user" (name) VALUES (%(name)s) RETURNING "user".id
{'name': 'rory'}

INSERT INTO keyword (keyword) VALUES (%(keyword)s) RETURNING keyword.id
{'keyword': 'chicken'}

INSERT INTO user_keyword (user_id, keyword_id, special_key) VALUES (%(user_id)s, %(keyword_id)s, %(special_key)s)
{'keyword_id': 1, 'special_key': None, 'user_id': 1}

DELETE FROM user_keyword WHERE user_keyword.user_id = %(user_id)s AND user_keyword.keyword_id = %(keyword_id)s
{'keyword_id': 1, 'user_id': 1}

Now a reasonable person would ask, "isn't that inconsistent?" 现在一个理智的人会问,“这不是不一致吗?” And at the moment I'd say, "absolutely". 而目前我会说,“绝对”。 I need to look into the test cases to see what the rationale is for this difference in behavior, I've identified in the code why it occurs in this way and I'm pretty sure this difference in how an "orphan" is considered for "pending" versus "persistent" objects is intentional, but in this particular permutation obviously produces a weird result. 我需要查看测试用例以了解这种行为差异的基本原理,我已经在代码中确定了为什么它会以这种方式出现,而且我很确定这种“孤儿”如何被考虑的区别“待定”与“持久”对象是故意的,但在这种特定的排列中显然会产生奇怪的结果。 I might make a change in 0.8 for this if I can find one that is feasible. 如果我能找到一个可行的话,我可能会在0.8中做出改变。

edit: http://www.sqlalchemy.org/trac/ticket/2655 summarizes the issue which I'm going to have to think about. 编辑: http//www.sqlalchemy.org/trac/ticket/2655总结了我将要考虑的问题。 There is a test for this behavior specifically, need to trace that back to its origin. 特别是对这种行为进行了测试,需要追溯到它的起源。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM