On Jul 3, 2013, at 4:33 PM, Josh Kuhn <deontologic...@gmail.com> wrote:

> I'm trying to get a certain access pattern to work and I need a bit of help:
> 
> https://gist.github.com/deontologician/5922496
> 
> What I'm trying to do is use an association proxy to create a view of a 
> collection that looks like a list of dictionaries (for serializing to json). 
> I also want to update that collection y receiving one of these dictionaries 
> from the user.
> 
> The problem is, I have to also keep two fields in sync that the users 
> "shouldn't see". In the example, it's widget_id and machine_id. widget_id is 
> easy, because it's the foreign key to the owner of the collection, so 
> sqlalchemy sets that for me. The problem is that the machine_id needs to be 
> kept in sync as well, but it refers to an object "one level up". I've tried 
> adding a validator to the collection under the proxy, but it only checks on 
> append, so initially null fields that the server sets aren't handled the way 
> SQLA handles the foreign_key field.
> 
> Is there an easier way to sync up the Gadget's machine_id field with the 
> Widget's machine_id field than just having a listener for every set event on 
> machine_id go through the entire collection and set it on all the objects?

Gadget.machine_id is a denormalized copy of Widget.machine_id, so at some 
point, if you have a Widget with 20 Gadgets, you need 20 Gadget rows to be 
modified.  

If you want to just go mass update here, you can use an UPDATE statement to 
just hit all the Gadget.machine_ids at once, since Gadget is dependent on 
Widget they might not all be present when a Widget is inserted so you can hit 
this in after_flush().  Iterate through session.new and session.dirty, look for 
Widget objects, and for each one emit an UPDATE to all gadgets with that 
machine_id.  Do the UPDATE through Session.execute() so it's within the same 
transaction.

Alternatively you could do the same thing but iterate through Gadgets instead.  
Recent SQLAlchemy versions will emit a second flush if changes are detected 
when a flush() completes, so it will reflush those extra changes.


-- 
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to sqlalchemy+unsubscr...@googlegroups.com.
To post to this group, send email to sqlalchemy@googlegroups.com.
Visit this group at http://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/groups/opt_out.


Reply via email to