On Oct 4, 2010, at 2:35 PM, Mark Erbaugh wrote:

> I'm trying to use a relationship that uses a set as the collection_class by 
> setting the collection_class parameter to set.
> 
> I chose a set since there should only be one instance corresponding to a give 
> table row since it is enforced by a foreign key on the many side.
> 
> When initially populating the data, I found that I can add two objects that 
> were instantiated with the same data. This makes sense because by default 
> when Python compares two instances it looks at their object id and since 
> these are two separate objects, there is no duplication. I added __hash__, 
> __cmp__ and __eq__ methods to the class so that instances with the same data 
> compare equal.
> 
> Is this the correct way to use a set as a collection_class?

I had to try this out, since it wasn't obvious to me what the behavior of a 
native "set" is - Jason Kirtland wrote the set instrumentation as well as all 
the collection tests in this area.    This instrumentation tests the incoming 
member for existing membership in the target set, and if already present, no 
attribute event is emitted - this event is what cascades the "save" operation 
to the child member, places it in the session for flush.    It appears that the 
set accepts only the first member upon add(), and the subsequent member with 
the same hash identity does not replace the existing member.   In fact it has 
to do it this way for our instrumentation to be reasonably possible - if the 
set instead performed an implicit "replace", there would be no efficient way to 
get at the "replaced" identity.   

So you should be seeing that your subsequent object being added to the set on 
top of an existing hash member does not enter the Session at all or get 
persisted.


-- 
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To post to this group, send email to sqlalch...@googlegroups.com.
To unsubscribe from this group, send email to 
sqlalchemy+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en.

Reply via email to