Auto_increment custom Primary Key in Peewee model
Asked Answered
I

4

5

I want a primary key id field to be Bigint

class Tweets(Model):
    id = BigIntegerField(primary_key=True)
    ...

But it needs to be auto_incremented and I can't find a way in the Peewee docs. Please suggest if it's possible.

Update: I'm using MySql db.

Inconsecutive answered 27/6, 2014 at 11:52 Comment(0)
G
4

Peewee automatically generates an integer id column serving as primary key, having the auto_increment property. This is true for any table you create with Peewee.

It is very likely that IntegerField is enough for your needs; BigIntegerField is very rarely useful. Will you really need numbers bigger than 2147483647? Will you insert more than two billion rows?

See: http://dev.mysql.com/doc/refman/5.5/en/integer-types.html

Griffon answered 30/6, 2014 at 6:43 Comment(2)
It would be useful for a slightly large scale application. 2147483647 is not a very big number for computer.Auscultate
Depends on the application. But you are right in this particular case, as I guess tweets are of this order of magnitude.Griffon
P
3

Peewee, as of 3.1, includes a BigAutoField which is an auto-incrementing integer field using 64-bit integer storage. Should do the trick:

http://docs.peewee-orm.com/en/latest/peewee/api.html#BigAutoField

Philippine answered 16/3, 2018 at 19:23 Comment(1)
Thanks ! This is the up to date answer. Nice and clear.Randyranee
I
2

I think the most convenience answer is by using SQL constraints:

import peewee

class MyModel(peewee.Model):
    id = peewee.BigIntegerField(primary_key=True, unique=True,
            constraints=[peewee.SQL('AUTO_INCREMENT')])
Ingemar answered 16/3, 2018 at 10:56 Comment(1)
the code snippet above works pretty well with peewee==2.10.1Ingemar
H
1

Looks like this should help.

After creating table, do:

db.register_fields({'primary_key': 'BIGINT AUTOINCREMENT'})

After that when you say

class Tweets(Model):
    id = PrimaryKey()
    ...
    class Meta():
        db = db

Then in mysql that field will appear as BigInt with auto increment

Hallee answered 30/11, 2014 at 20:19 Comment(1)
ps: may be you also should replace id with pk .. not sure for that.Hallee

© 2022 - 2024 — McMap. All rights reserved.