Reputation: 65
I want to create objects of a given class Task, store some of them on the database employing SQLAlchemy, and discard the others. At the moment this class is created with:
Base = declarative_base()
class Task(Base):
__tablename__ = 'tasks'
id = Column(Integer, primary_key=True)
hostID = Column(Integer, ForeignKey('hosts.id'))
name = Column(String)
host = relationship("Host", backref="tasks", cascade_backrefs=False)
def __init__(self, host, name):
self.host = host
self.name = name
class Host(Base):
__tablename__ = 'hosts'
id = Column(Integer, primary_key=True)
hostname = Column(String)
When I perform
newTask1= GridTask(myHost, myName)
Session.add(newTask1)
Session.commit()
newTask2= GridTask(myHost, otherName)
Session.commit()
The first task is stored on the first commit -which is OK- and the second one is stored on the second commit, what I want to avoid.
My question is, how can I declare Task and Host classes so a given instance is persisted on the DB only when explicitly asked for? I am correctly employing "cascade_backrefs"?
Thank you for your help.
Upvotes: 1
Views: 769
Reputation: 75187
its the other way around (don't worry, I don't even know what direction to use until I just try a simple test):
class Task(Base):
__tablename__ = 'tasks'
id = Column(Integer, primary_key=True)
hostID = Column(Integer, ForeignKey('hosts.id'))
name = Column(String)
host = relationship("Host", backref=backref("tasks", cascade_backrefs=False))
def __init__(self, host, name):
self.host = host
self.name = name
this is because the mechanism is:
Upvotes: 1