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?

Matthias
  • 9,817
  • 14
  • 66
  • 125

1 Answers1

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')
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • 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 Apr 20 '13 at 17:34
  • @coleifer: adjusted the wording. – Martijn Pieters Apr 20 '13 at 20:41
  • 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. – OzzyTheGiant Oct 05 '16 at 21:01