Skip to content Skip to sidebar Skip to footer

Why Is Peewee Including The 'id' Column Into The Mysql Select Query?

I am trying to learn how to use peewee with mysql. I have an existing database on a mysql server with an existing table. The table is currently empty (I am just testing right now)

Solution 1:

Most simple active-record pattern ORMs need an id column to track object identity. PeeWee appears to be one of them (or at least I am not aware of any way to not use an id). You probably can't use PeeWee without altering your tables.

Your existing table doesn't seem to be very well designed anyway, since it appears to lack a key or compound key. Every table should have a key attribute - otherwise it is impossible to distinguish one row from another.

If one of these columns is a primary key, try adding a primary_key=True argument as explained in the docs concerning non-integer primary keys

date = DateField(primary_key=True)

If your primary key is not named id, then you must set your table's actual primary key to a type of "PrimaryKeyField()" in your peewee Model for that table.

You should investigate SQLAlchemy, which uses a data-mapper pattern. It's much more complicated, but also much more powerful. It doesn't place any restrictions on your SQL table design, and in fact it can automatically reflect your table structure and interrelationships in most cases. (Maybe not as well in MySQL since foreign key relationships are not visible in the default table engine.) Most importantly for you, it can handle tables which lack a key.

Solution 2:

If your primary key column name is other than 'id' you should add additional field to that table model class:

classTable(BaseModel):
    id_field =PrimaryKeyField()

That will tell your script that your table has primary keys stored in the column named 'id_field' and that column is INT type with Auto Increment enabled. Here is the documentation describing field types in peewee.

If you want more control on your primary key field, as already pointed by Francis Avila, you should use primary_key=True argument when creating field:

classTable(BaseModel):
    id_field =CharField(primary_key=True)

See this link on non-integer primary keys documentation

Solution 3:

You have to provide a primary_key field for this model. If your table doesn't have a single primary_key field(just like mine), a CompositeKey defined in Meta will help.

primary_key = peewee.CompositeKey('date', 'team')

Solution 4:

You need to us peewee's create table method to create the actual database table before you can call select(), which will create an id column in the table.

Post a Comment for "Why Is Peewee Including The 'id' Column Into The Mysql Select Query?"