On Apr 20, 2012, at 8:45 AM, Eric Lemoine wrote:

> On Mon, Apr 16, 2012 at 10:49 PM, Eric Lemoine
> <eric.lemo...@camptocamp.com> wrote:
>> Hi
>> 
>> I'd like to use an associationproxy for a simple many-to-one relationship:
>> 
>> class Child(Base):
>>     __tablename__ = 'child'
>>     id = Column(Integer, primary_key=True)
>>     name = Column(Unicode)
>> 
>> class Parent(Base):
>>     __tablename__ = 'parent'
>>     id = Column(Integer, primary_key=True)
>>     child_id = Column(Integer, ForeignKey('child.id')
>>     child_ = relationship(Child)
>>     child = association_proxy('child_', 'name', creator=)
>> 
>> Now 'child' is a read-only, dictionary-like table. I never want to insert
>> new rows in this table.
>> 
>> So I actually pass the following "creator" to the association_proxy
>> constructor:
>> 
>> def creator(name):
>>     return Session.query(Child).filter_by(name=name).first()

>> 
>> That does the job for "create". But I cannot find a solution for "update".
>> On update I'd like to replace the current Child object in the Parent object
>> by a new Child object read from the 'child' table.
>> 
>> Using a specific setter (in a getset_factory) does not work for me, as the
>> setter receives the Child object (and the value), not the Parent object –
>> I'd need a ref to the Parent object to be able to change its Child object in
>> child_.
>> 
>> Maybe I'm doing it all wrong and using an associationproxy is not the way to
>> go for that case.

the associationproxy is good for collections but in this case I'm not sure what 
you're getting versus a regular @property or @hybrid_property.   

I will note that I think I do a use case a little bit similar to this, where 
Parent.children is a dictionary keyed on name.  But instead of sticking 
Session.query() into creator, I use a recipe similar to the unique object 
recipe: http://www.sqlalchemy.org/trac/wiki/UsageRecipes/UniqueObject .

If the associationproxy is doing it's job, modifying "Parent.child", as a 
string, should be updating Parent._child.name with the new value.     If you 
wanted to replace that with "just swap this other Child in", you could do that 
in a before_flush() event, not unlike the insert versions recipe: 
http://www.sqlalchemy.org/trac/wiki/UsageRecipes/VersionedRows

but just sticking with @property or hybrid might be more straightforward here, 
if it works.

-- 
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To post to this group, send email to sqlalchemy@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