SQLAlchemy:随机唯一整数?

时间:2016-08-03 22:42:06

标签: python random sqlalchemy unique identifier

我可以这样做,将列类型设置为唯一字符串:

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

但我想生成 random-unique-integer ,而不是random-unique-string。

任何想法如何做到这一点?

uuid.uuid4()。INT

感谢。如果我可以重新指定:)是否有办法使其适合DB Integer类型。

1 个答案:

答案 0 :(得分:3)

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)