Fary El Grande
Fary El Grande

Reputation: 65

Creating non persistent objects with SQLAlchemy: wrong employment of backref in a relationship?

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

Answers (1)

zzzeek
zzzeek

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:

  1. new Task
  2. Task.host = somehost
  3. backref kicks in, has the effect of somehost.tasks.append(task)
  4. its step #3 that makes "task" a child of "host" and therefore cascaded in
  5. cascade_backrefs=False on tasks means, "if this event started with a backref (in this context "host" is the backref), don't run the save-update cascade.

Upvotes: 1

Related Questions