sten
sten

Reputation: 7486

SQLAlchemy : random Unique integer?

I can do this to set column type to be unique string :

    uuid = Column(String,  default=lambda: str(uuid.uuid4()), unique=True)

but I want to generate random-unique-integer, not random-unique-string.

any idea how to do that ?


uuid.uuid4().int

thanks. If I can respecify :) is there a way to fit it into DB Integer type.

Upvotes: 5

Views: 7622

Answers (2)

Astariul
Astariul

Reputation: 2354

The INTEGER type in DB is 4 bytes (32 bits).

The uuid.uuid4().int generate a 128 bits integer.

So just ignore most of the bits (with bitwise shift operator) :

uuid = Column(Integer,  default=lambda: uuid.uuid4().int >> (128 - 32), unique=True)

Upvotes: -1

talhasch
talhasch

Reputation: 367

from random import randint 

def random_integer():
    min_ = 100
    max_ = 1000000000
    rand = randint(min_, max_)

    # possibility of same random number is very low.
    # but if you want to make sure, here you can check id exists in database.
    from sqlalchemy.orm import sessionmaker
    db_session_maker = sessionmaker(bind=your_db_engine)
    db_session = db_session_maker()
    while db_session.query(Table).filter(uuid == rand).limit(1).first() is not None:
        rand = randint(min_, max_)

    return rand

class Table(Base):
    uuid = Column(String,  default=random_integer, unique=True)

Upvotes: 5

Related Questions