2

I'm using flask-sqlalchemy. My class is:

class Game(db.Model):
    userid = db.Column(db.Integer, primary_key=True)
    gameid = db.Column(db.Integer, primary_key=True)

gameid is set to auto-increment in the database.

When I run this function:

@app.route("/requestgame")
def requestgame():
    game = Game()
    game.userid = session["userid"]
    db.session.add(game)
    db.session.commit()
    session["gameid"] = game.gameid
    return "gameid {}".format(game.gameid)

I get "ObjectDeletedError: Instance '' has been deleted, or its row is otherwise not present."

How can I get the gameid to return?

It looks like someone asked the same question about regular SQLAlchemy here: SQLAlchemy Obtain Primary Key With Autoincrement Before Commit but I have tried the recommended solution (calling session.flush()) and it doesn't seem to make any difference.

Community
  • 1
  • 1
matthewk
  • 1,841
  • 17
  • 31
  • you mean you tried `db.sessions.flush()`, right? – Paolo Casciello Feb 03 '14 at 14:09
  • No, `db.session.flush()`. `db.sessions.flush()` gives the error `"AttributeError: 'SQLAlchemy' object has no attribute 'sessions'"`. – matthewk Feb 03 '14 at 18:03
  • I guess you got an issue because you have two columns marked as primary key. – Dmitry Vakhrushev Feb 03 '14 at 18:34
  • Why? http://packages.python.org/Flask-SQLAlchemy/models.html says "Multiple keys can be marked as primary keys in which case they become a compound primary key." – matthewk Feb 03 '14 at 19:02
  • autoincrement in databases typically applies to a single-column, integer primary key. if you have a composite key, the rules for "autoincrement" vary by platform (e.g. sqlite it goes away completely), but unless you have explicit SEQUENCE objects in use, it will still be just one column max for "auto". – zzzeek Feb 10 '14 at 05:25
  • I am in a similar situation. Two primary keys. One is also a foreign key. And the second autoincrements via a trigger. Is there a way for SQLAlchemy to handle this? I guess not, because it has no way of tracing the object to the row. Perhaps it's best to handle this in Python instead. – Jonathan Biemond Aug 06 '23 at 21:40

0 Answers0