On 7/18/15 5:22 AM, Martin Pengelly-Phillips wrote:
Hello,

I'm curious about the behaviour of foreign keys when modifying collections as I want to be able to get the value before flush for some business logic validation.

The following is a cut down version of the association list example:

|
importuuid

fromsqlalchemy importColumn,ForeignKey,Integer,String,create_engine
fromsqlalchemy.orm importSession,relationship,backref
fromsqlalchemy.ext.declarative importdeclarative_base

Base=declarative_base()


classTreeNode(Base):
    __tablename__ ='tree'

    id =Column(String(36),primary_key=True)

    parent_id =Column(Integer,ForeignKey(id))

    children =relationship(
'TreeNode',backref=backref('parent',remote_side=id)
)

def__init__(self,id=None,*args,**kwargs):
ifid isNone:
            id =str(uuid.uuid4())
self.id =id
super(TreeNode,self).__init__(*args,**kwargs)


if__name__ =='__main__':
    engine =create_engine('sqlite://')
Base.metadata.create_all(engine)

    session =Session(engine)

    node =TreeNode()
    session.add(node)
printnode.id # some uuid

    child_node =TreeNode()
    node.children.append(child_node)

# Question: Why is parent_id not set to node.id even though it was available?
printchild_node.parent_id

|

Note that the child_node.parent_id is None even though the referenced value was present in the session. I know a flush will fix this, but I want to check this value is not None for certain 'types' of node before flush if possible.

Is there a way to configure that behaviour or should I be creating my own collection listeners to handle this?

yes use either the AttributeEvents.append() event or SessionEvents.before_flush().



cheers,


Martin
--
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 <mailto:sqlalchemy+unsubscr...@googlegroups.com>. To post to this group, send email to sqlalchemy@googlegroups.com <mailto:sqlalchemy@googlegroups.com>.
Visit this group at http://groups.google.com/group/sqlalchemy.
For more options, visit https://groups.google.com/d/optout.

--
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/d/optout.

Reply via email to