2
聯繫人以1,2,3的順序添加到列表中,但查詢返回顯示列表是奇怪的順序2,1,3。只有下面的測試才能通過,請注意提交前後的最後3行。添加到列表中的項目不在預期的順序
class Staff(mydb.Model):
__tablename__ = 'STAFF'
staff_id = mydb.Column(mydb.String(20), primary_key = True)
first_name = mydb.Column(mydb.String(64))
last_name = mydb.Column(mydb.String(64))
email = mydb.Column(mydb.String(62), unique=True, nullable = False)
password = mydb.Column(mydb.String(), nullable = False)
class StaffContact(mydb.Model):
__tablename__ = 'STAFF_CONTACT'
staff_id = mydb.Column(mydb.String(20), mydb.ForeignKey('STAFF.staff_id'), primary_key = True)
department = mydb.Column(mydb.String(50), primary_key = True)
office = mydb.Column(mydb.String(50))
phone = mydb.Column(mydb.String(15))
staff_obj = mydb.relationship('Staff', backref='contact_list')
def test_add_contact_to_new_staff(self):
staff = Staff(
staff_id='QWE',
first_name='QWE',
last_name='QWE',
email='QWE',
password='QWE')
mydb.session.add(staff)
mydb.session.commit()
staff_rst1 = mydb.session.query(Staff).filter_by(staff_id='QWE').first()
self.assertEquals(staff_rst1, staff)
self.assertIs(staff_rst1, staff)
contact_1 = StaffContact(
staff_id = 'XYZ',
department='XYZ',
office='XYZ',
phone='XYZ'
)
contact_2 = StaffContact(
staff_id = 'ABC',
department='ABC',
office='ABC',
phone='ABC'
)
contact_3 = StaffContact(
staff_id = 'EFG',
department='EFG',
office='EFG',
phone='EFG'
)
staff_rst1.contact_list=[contact_1, contact_2, contact_3]
mydb.session.add(staff_rst1)
self.assertIs(staff_rst1.contact_list[0], contact_1)
self.assertIs(staff_rst1.contact_list[1], contact_2)
self.assertIs(staff_rst1.contact_list[2], contact_3)
mydb.session.commit()
staff_rst2 = mydb.session.query(Staff).filter_by(staff_id='QWE').first()
self.assertIs(staff_rst2.contact_list[0], contact_2)
self.assertIs(staff_rst2.contact_list[1], contact_1)
self.assertIs(staff_rst2.contact_list[2], contact_3)
只是爲了調試的目的,你可以嘗試刪除行'mydb.session.add(staff_rst1)'並檢查你是否仍然面臨這個問題? –