There are two classes: User and Question
A user may have many questions, and it also contains a question_count
to record the the count of questions belong to him.
So, when I add a new question, I want update the question_count of the
user. At first, I do as:
question = Question(title='aaa', content='bbb')
Session.add(question)
Session.flush()
user = question.user
### user is not None
user.question_count += 1
Session.commit()
Everything goes well.
But I wan’t to use event callback to do the same thing. As following:
from sqlalchemy.orm.interfaces import MapperExtension
class Callback(MapperExtension):
def after_insert(self, mapper, connection, instance):
user = instance.user
### user is None !!!
user.question_count += 1
class Question(Base):
__tablename__ = "questions"
__mapper_args__ = {'extension':Callback()}
....
-
Note in the “after_insert” method:
instance.user # -> Get None!!!Why?
-
If I change that line to:
Session.query(User).filter_by(id=instance.user_id).one()I can get the user successfully, But: the user can’t be updated!
Look I have modified the user:
user.question_count += 1But there is no ‘update’ sql printed in the console, and the
question_countare not updated. -
I try to add
Session.flush()orSession.commit()in the
after_insert()method, but both cause errors.
Is there any important thing I’m missing? Please help me, thank you
The author of sqlalchemy gave me an useful answer in a forum, I copy it here:
And, as I tried, I found we should update the
user.question_countinafter_flush