我有2个模型:Games
和GamesHealth
。后者指的是前者ForeignKey
。当我尝试插入GamesHealth
表中已存在game_slug
的{{1}}对象时,它仍会尝试在Games
表中插入一些内容。
这是错误:
games
这是最小的完整代码:
sqlalchemy.exc.OperationalError: (_mysql_exceptions.OperationalError) (1048, "Column 'game_name' cannot be null") [SQL: u'INSERT INTO games (game_name, game_slug) VALUES (%s, %s)'] [parameters: (None, 'rural-racer')]
我错过了什么?是因为from sqlalchemy import Column, ForeignKey, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine
import config
Base = declarative_base()
metadata = Base.metadata
class Game(Base):
__tablename__ = 'games'
game_id = Column(Integer, primary_key=True)
game_name = Column(String(70), nullable=False)
game_slug = Column(String(70), nullable=False, unique=True)
class GamesHealth(Game):
__tablename__ = 'games_health'
game_slug = Column(ForeignKey(u'games.game_slug', ondelete=u'CASCADE', onupdate=u'CASCADE'), primary_key=True)
class Database(object):
def __init__(self):
db_url = config.DEVELOPMENT_DB_URL
self.engine = create_engine(db_url, echo=False)
self.session = Session(self.engine)
if __name__ == '__main__':
db = Database()
health = GamesHealth(game_slug='rural-racer')
db.session.add(health)
db.session.commit()
中的game_slug
是外键还是主键?