0

I am new to peewee, so please forgive me if this is a stupid question. I have searched on Google and in the peewee cookbook, but found no solution so far.

So, I have the following models to four of my DB tables:

class games_def(Model):
    id = PrimaryKeyField()
    name = TextField()
    class Meta:
        database = dbmgr.DB

class users_def(Model):
    id = PrimaryKeyField()
    first_name = TextField()
    last_name = TextField()
    class Meta:
        database = dbmgr.DB

class sessions(Model):
    id = PrimaryKeyField()
    game = ForeignKeyField(games_def, related_name = 'sessions')
    user = ForeignKeyField(users_def, related_name = 'sessions')
    comment = TextField()
    class Meta:
        database = dbmgr.DB

class world_states(Model):
    session = ForeignKeyField(sessions)
    time_step = IntegerField()
    world_state = TextField()
    class Meta:
        database = dbmgr.DB

Using these models I connect to an SQLite3 DB via peewee, which works fine. After the connection has been established I do the following in my main Python code:

models.world_states.create(session = 1, time_step = 1)

However, this gives me the following error:

sqlite3.OperationalError: table world_states has no column named session_id

That is basically correct, the table world_state does indeed not contain such a column.
However, I cannot find any reference to "session_id" in my code at all.

Whe does peewee want to use that "session_id" colum name?
Do I miss something essentially here?

1 Answer 1

3

When you specify a ForeignKeyField() peewee expects to use a column ending in _id based on their own name. Your wold_states.session field thus results in an column named session_id.

You can override this by setting db_column for that field:

class world_states(Model):
    session = ForeignKeyField(sessions, db_column='session')
Sign up to request clarification or add additional context in comments.

3 Comments

This is correct, thanks Martijn! The only thing I would add would be that if you created your table then added a field, peewee will not "automatically" add the column on your database table. This must be done manually.
@coleifer: adjusted the wording.
Oh my god! Thank you so much @MartijnPieters for this. After FOUR agonizing days I finally figured out my problem. I had the same thing going on and I checked the docs but the way they have it written out confused me and I had no idea db_column was to actually specify which column to point to.

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.