I am trying to insert a row for a table which has auto_increment as well as some foreign keys. All the foreign keys exist. But it throws error.
sqlalchemy.orm.exc.FlushError: Instance Stock at 0x9cf062c has a NULL identity key. If this is an auto-generated value, check that the database table allows generation of new primary key values, and that the mapped Column object is configured to expect these generated values. Ensure also that this flush() is not occurring at an inappropriate time, such as within a load() event.
Even insertion of record via MySQL, by copy-paste SQL produced by echo=True, is executing.
Stock Class
class Stock(Base):
__tablename__ = 'Stock'
Code = Column('Code',String(8),primary_key=True)
Symbol = Column('Symbol',String(128))
ListingName = Column('ListingName',String(256))
ListingDate = Column('ListingDate',DateTime())
RecordAddedDate = Column('RecordAddedDate',DateTime())
HomeCountry = Column('HomeCountry',ForeignKey('Country.Code'))
PrimaryExchange = Column('PrimaryExchange',ForeignKey('Exchange.Code'))
BaseCurrency = Column('BaseCurrency',ForeignKey('Currency.Code'))
InstrumentType = Column('InstrumentType',ForeignKey('Instrument.InstrumentType'))
Record insertion
Engine = sqlalchemy.create_engine('mysql://user:pass@host/db',echo=True)
Session = sqlalchemy.orm.sessionmaker(bind=Engine)
SessionObj = Session()
NewStock = Stock()
NewStock.InstrumentType = 'Stock'
NewStock.Symbol = 'MSFT'
NewStock.ListingName = 'Microsoft'
NewStock.HomeCountry = 'IN'
NewStock.PrimaryExchange = 'NSEOI'
NewStock.BaseCurrency = 'INR'
NewStock.ListingDate = datetime.datetime.now().strftime("%Y%m%d")
NewStock.RecordAddedDate = datetime.datetime.now().strftime("%Y%m%d")
print NewStock
SessionObj.add(NewStock)
SessionObj.flush()
print NewStock.Code
SHOW CREATE TABLE Stockdoes it showAUTO_INCREMENT?