views:

27

answers:

1

The title may be not exactly, but I don't know how to express it.

I have 3 class: User, Question, Answer. The simple code is:

Session = scoped_session(sessionmaker())
Base = declarative_base()

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)

    questions = relationship('Question', backref="user")
    answers = relationship('Answer', backref="user")

class Question(Base):
     __tablename__ = 'questions'
     id = Column(Integer, primary_key=True)
     user_id = Column(Integer, ForeignKey('users.id'))

     answers = relationship('Answer', backref="user")

class Answer(Base):
     __tablename__ = 'answers'
     user_id = Column(Integer, ForeignKey('users.id'))
     question_id = Column(Integer, ForeignKey('questions.id'))

     id = Column(Integer, primary_key=True)

Now, A user asked a question, so there will be an answer created:

user = get_user_from_session()
question = get_question(question_id)

# create answer
answer = Answer()
answer.user = user
answer.question = question

Session.add(answer)  # !!!
Session.commit()

I hope the answer will be inserted to database, but unfortunately, there is an error reported:

 AttributeError: 'module' object has no attribute '_sa_instance_state'

Is there something I've missed? How to fix it?


UPDATE

Thanks for @dhaffey, I've fixed the typos. I recreate a test file to test this, found no error happened again, but answer.user_id and answer.question_id are null in database after commit.

This is my code, you can run it directly.

from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import *

engine = create_engine('sqlite:///test.sqlite', echo=True)
Session = scoped_session(sessionmaker())
Base = declarative_base()

Base.metadata.bind=engine

class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    questions = relationship('Question')
    answers = relationship('Answer')

class Question(Base):
    __tablename__ = 'questions'
    id = Column(Integer, primary_key=True)
    user_id = Column(Integer, ForeignKey('users.id'))
    title = Column(String)
    answers = relationship('Answer')

class Answer(Base):
    __tablename__ = 'answers'
    user_id = Column(Integer, ForeignKey('users.id'))
    question_id = Column(Integer, ForeignKey('questions.id'))

    id = Column(Integer, primary_key=True)

Base.metadata.create_all()

user = User()
user.name = 'aaa'
Session.add(user)
Session.flush()

question = Question()
question.title = 'ttt'
question.user = user
Session.add(question)
Session.flush()

answer = Answer()
answer.user = user
answer.question = question

Session.add(answer)
Session.commit()

print answer.id # not None

found = Session.query(Answer).filter_by(id=answer.id).one()

print found.user.name # not None
print found.question.title # not None

# !!! It seems all models are saved correctly,
# but please open the test.sqlite database, (not querying by sqlahchemy)
# the question.user_id and answer.user_id and answer.question_id are null
A: 

Your class declarations don't "compile" for me, so I'm wondering if you've run this code, and which SQLAlchemy version you're using if so. The line

user_id = Column(Integer, ForeignKey='users.id')

raises

sqlalchemy.exc.ArgumentError: Unknown arguments passed to Column: ['ForeignKey']

with SQLAlchemy 0.6.4. You're trying to declare the foreign key with a keyword argument, but the correct usage is to construct a ForeignKey object and pass it positionally, like this:

user_id = Column(Integer, ForeignKey('users.id'))

With the foreign keys fixed, your example works as expected for me.

Note that you don't need to explicitly provide the primaryjoin argument on these relationships when the corresponding foreign keys are appropriately declared - SQLAlchemy infers the correct join.

dhaffey
@dhaffey, sorry, the `ForeignKey` mistake is a typo(I wrote the code by hand, not copied). I just fixed it and tried it again, found no error happened this time(maybe the sample code is much easier than the actual one), but the `answer.user_id` and `answer.question_id` are null in database. So, `answer.user = user` and `answer.question = question` actually does nothing. Could you run your test again and check this?
Freewind
When you fixed the other typos you introduced a new error by removing the `backref` arguments to some of the relationships. Without those, the `user` and `question` attributes are just regular Python attributes with no database backing. The reason you get them back with immediate queries is that SQLAlchemy returns the same instance (with the same transient Python state) from its identity map. Specifying `backref='user'` for `User.questions` and `User.answers`, and `backref='question'` for `Question.answers` turns them back into database-backed properties.
dhaffey
Very sorry, this is a new typo. And the updated code is what I was using when I tested. There is the same error: the data in database has no `user_id` and `question_id`
Freewind
It looks like now you've updated the original version of your code with `backref` arguments, but I think you're probably still testing with the code further down in your question that doesn't have them. If I use the first set of class definitions, the line `user = User()` raises an exception because you pasted `backref="user"` for `Question.answers`, instead of `backref="question"`. If I fix that and run your test, everything ends up in the database as expected.
dhaffey