简体   繁体   中英

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 ,

why it is returning None ? Shall i write test case as assertIsNone .

Your student object is transient and does not have any identity in the database. Assuming student_id is generated automatically, it will be None till you persist this object in the session.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM