My problem is as follows. I ve got a directed graph structure in sqlalchemy with polymorphic vertices and I d like to restrict the edge creation type dependant. The following code defines the graph structure.
from sqlalchemy import Column, ForeignKey, Integer
from sqlalchemy.orm import backref, relationship
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Edge(Base):
__tablename__ = edge
head_id = Column(Integer, ForeignKey( vertex.id ), primary_key=True)
tail_id = Column(Integer, ForeignKey( vertex.id ), primary_key=True)
class Vertex(Base):
__tablename__ = vertex
id = Column( Integer, primary_key=True )
predecessors = relationship( Vertex ,
secondary= edge ,
primaryjoin="Vertex.id==Edge.head_id",
secondaryjoin="Vertex.id==Edge.tail_id",
backref= successors )
type = Column( String(50) )
__mapper_args__ = {
polymorphic_identity : Vertex ,
polymorphic_on :type
}
图表的构造非常简单
#creates two vertices with a directed edge from v1 to v2
v1 = Vertex()
v2 = Vertex()
v1.successors.append(v2) # v1->v2
The problem is How can i restrict the edge creation type dependant. E.g. Edges from class A to class B are allowed but not vice versa.
class A(Vertex):
pass
class B(Vertex):
pass
v1 = A()
v2 = B()
v1.successors.append(v2) #allowed
v2.successors.append(v1) #forbidden