[Python] sqlalchemy - clear list and add item - null violation for foreign key

Discussão em 'Python' iniciado por Stack, Março 24, 2025.

  1. Stack

    Stack Membro Participativo

    I try to clear a list and add an item to it. I get IntegrityError('(psycopg2.errors.NotNullViolation) null value in column "game_id" of relation "player" violates not-null co...2, null).\n')

    class Game(Base):
    __tablename__ = "game"
    game_id: int = Column(INTEGER, primary_key=True, server_default=Identity(always=True, start=1, increment=1, minvalue=1, maxvalue=2147483647, cycle=False, cache=1), autoincrement=True)
    players = relationship('Player', back_populates='game')

    class Player(Base):
    __tablename__ = "player"
    player_id: int = Column(INTEGER, primary_key=True, server_default=Identity(always=True, start=1, increment=1, minvalue=1, maxvalue=2147483647, cycle=False, cache=1), autoincrement=True)
    game_id: int = Column(INTEGER, ForeignKey('game.game_id'), nullable=False)
    game = relationship('Game', back_populates='players')


    game = session.query(Game).first()
    game.players.clear()
    player = Player(name='john')
    game.players.append(player)
    session.commit()

    Continue reading...

Compartilhe esta Página