Background:

I have a two model classes where one is a parent of the other via a one to 
many relationship. The parent has a collection of the children with a 
backref:

class Parent(base):
  __tablename__ = "parent_table"


  parent_key = Column(String, primary_key=True)
  some_quantity = Column(Integer)
  current_children_quantity = Column(Integer)
  children = relationship("Parent", backref="parent_table")

  @validates("children")
  def validate_children(self, key, child):
    new_quantity = self.current_children_quantity + child.some_quantity
    if self.some_quantity < new_quantity:
      raise Exception
    return child


class Child(base):
  __tablename__ = "child_table"


  child_key = Column(String, primary_key=True)
  some_quantity = Column(Integer)
  parent_key = Column(String, ForeignKey("parent_table.parent_key"))



When I add a child to the parent collection, I have to make sure that the 
sum of the "some_quantity" fields of all children on the same parent do not 
exceed the
some_quantity field of the parent. The field current_children_quantity 
keeps track of the sum of the children. In order to automatically do this, 
I set up an
event listener:

@event.listens_for(Parent.children, "append")
def increment_quantity(target, value, initiator):
  target.current_children_quantity += value.some_quantity

The problem is that the "append" event fires before the validator. This 
results in the parent's current_children_quantity being updated
before the child append can be validated. Because of this, in the case 
where twice the child's some_quantity added to current_children_quantity
exceeds the parent's some_quantity, the append doesn't happen, even though 
it should.

My (ugly) solution is to put the validation into the "append" event 
listener but there must be a better way! Can I control the order of events?
Maybe I'm not using all the tools at my disposal?

-- 
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 [email protected].
To post to this group, send email to [email protected].
Visit this group at https://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.

Reply via email to