SQLAlchemy update parent when related child changes

后端 未结 1 601
萌比男神i
萌比男神i 2020-12-30 16:52

I\'m trying to model an entity that as one or more one-to-many relationships, such that it\'s last_modified attribute is updated, when

  • a child is
相关标签:
1条回答
  • 2020-12-30 17:23

    Take this with a huge grain of salt, it "seems" to work, could explode:

    def rel_listener(t, v, i):
        t.last_modified = now()
    
    def listener(t, v, o, i):
        if t.config:
            t.config.last_modified = now()
    
    from sqlalchemy import inspect
    
    for rel in inspect(Config).relationships:
        event.listen(rel, 'append', rel_listener)
        event.listen(rel, 'remove', rel_listener)
    
    for col in inspect(ConfigParam).column_attrs:
        event.listen(col, 'set', listener)
    

    Problem is that the inspections make no exceptions and columns such as 'ID' and 'ConfigID' will be bound to event listeners.

    Another perhaps slightly less tedious form would be to just use a list of attributes to bind events to in a similar fashion:

    for attr in ['key', 'value']:
        event.listen(getattr(ConfigParam, attr), 'set', listener)
    

    This gives you control over what is bound to events and what is not.

    0 讨论(0)
提交回复
热议问题