[英]Why class instance return None when it has initialized
I had a class as below 我有一节课如下
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Student(Base):
__tablename__ = 'students'
student_id = Column(Integer, primary_key=True)
address = Column(String)
name = Column(String)
def __init__(self, address, name):
self.address = address
self.name = name
below is my call 以下是我的电话
def test_Student(self):
from School.Student import Student
address = 'India'
name = 'Team A'
student = Student(address,name)
print student.student_id
student.student_id is returning None
, student.student_id is returning None
,
why it is returning None ? 为什么它返回无? Shall i write test case as
assertIsNone
. 我应该把测试用例写成
assertIsNone
。
Your student
object is transient and does not have any identity in the database. 您的
student
对象是暂时的 ,并且在数据库中没有任何标识。 Assuming student_id
is generated automatically, it will be None
till you persist this object in the session. 假设
student_id
是自动生成的,在您将此对象保留在会话中之前,它将为None
。
session.add(student)
session.flush()
However, if you are writing tests, be careful that you do not commit your session (and hence add test data to the DB). 但是,如果您正在编写测试,请注意不要提交会话(因此将测试数据添加到数据库)。 This would involve opening a new transaction for every test and rolling it back at the end of the test
这将涉及为每个测试打开一个新事务,并在测试结束时将其回滚
您需要先保存学生才能获得自动增加的ID。
session.add(student)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.