I have two tables, "task" and "person", and m:m join table between
them, "t2p". The "Task" object has a relationship, "t2p_" that is
a list of all the associated "t2p" rows. Each of those has a "Person"
attribute for the associated "person" row.
I get a "table" row. I then change the t2p_[n].person attribute
to a different person.id number. I was hoping that sqlalchemy
would then know to update the .Person attribute on the same object
to match. But it doesn't. Code below illustrates; it prints
before change:
T2P(Person=<__main__.Person object at 0xb6e582cc>, person=20, task=1)
Person = Person(id=20, name='Dave')
after change:
T2P(Person=<__main__.Person object at 0xb6e582cc>, person=21, task=1)
Person = Person(id=20, name='Dave')
What is the best way to get the .Person attribute updated to match
a new value assigned to .person?
----
#!/usr/bin/python3
import sys, logging, pdb
from sqlalchemy import create_engine, Table, Column, Integer, String,
ForeignKey
from sqlalchemy.orm import relationship, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
logging.basicConfig()
class Table:
def __str__(self):
return self.__class__.__name__ + '(' \
+(', '.join('%s=%r'%(k,getattr(self,k))
for k in dir(self)
if not k.startswith('_') and k!='metadata' and
k!='prepare')) + ')'
class Task (Table, Base):
__tablename__ = 'task'
id = Column (Integer, primary_key=True)
name = Column (String(50))
t2p_ = relationship ('T2P')
class Person (Table, Base):
__tablename__ = 'person'
id = Column (Integer, primary_key=True)
name = Column (String(50))
class T2P (Table, Base):
__tablename__ = 't2p'
task = Column (Integer, ForeignKey('task.id'),
primary_key=True)
person = Column (Integer, ForeignKey('person.id'),
primary_key=True)
Person = relationship ('Person', uselist=0, load_on_pending=True)
logging.getLogger ('sqlalchemy.engine').setLevel (logging.DEBUG)
connectstr = 'sqlite://'
engine = create_engine (connectstr)
Base.metadata.create_all (engine)
session = sessionmaker (bind=engine)()
logging.getLogger ('sqlalchemy.engine').setLevel (logging.DEBUG)
session.add (Task (id=1,name='task1'))
session.add (Person (id=20,name='Dave'))
session.add (Person (id=21,name='John'))
session.add (T2P (task=1,person=20))
items = session.query(Task).order_by(Task.id).all()
print ('before change:\n', str(items[0].t2p_[0]), '\n Person =',
str(items[0].t2p_[0].Person))
items[0].t2p_[0].person=21
print ('after change:\n', str(items[0].t2p_[0]), '\n Person =',
str(items[0].t2p_[0].Person))
pass
--
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 http://groups.google.com/group/sqlalchemy?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.