0

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
1
  • Hint: what happens when you go to the MySQL shell and type SHOW CREATE TABLE Stock does it show AUTO_INCREMENT? Commented Sep 23, 2012 at 8:28

2 Answers 2

1

Add autoincrement=True to your column.

Sign up to request clarification or add additional context in comments.

2 Comments

It is not in your code; perhaps you should post the complete code you are using.
reckon autoincrement is optional, i didn't have it in original code but tried it after googling. updated with more code.
0

Got it. I had the column type as String, after converting to Integer worked fine.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.