python - SQL炼金术 : random Unique integer?

标签 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 类型。

最佳答案

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)

关于python - SQL炼金术 : random Unique integer?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38754816/

相关文章:

python - 在 PyCharm 中使用 Docker Image 作为 Python 解释器

python - Paypal 自适应支付 - 预批准请求导致 "Invalid request"错误

c# - map 生成器缺乏随机性

C# - 带种子的随机数

python + sqlalchemy : calling stored procedures in a loop

python - PyQt、SQLAlchemy - 哪些 session 适合?

python - 有什么办法可以用 Cython 获得 "interfaces"?

c++ - C++ 中的 normrnd 函数

python - 更改记录查询中的隔离级别或关闭事务

python - 如何将 Dask Dataframe 转换为 Dask Array?