Random ids in sqlalchemy (pylons)

后端 未结 3 1742
星月不相逢
星月不相逢 2021-02-09 20:28

I\'m using pylons and sqlalchemy and I was wondering how I could have some randoms ids as primary_key.

相关标签:
3条回答
  • 2021-02-09 21:04

    the best way is to use randomly generated UUIDs:

    import uuid
    
    id = uuid.uuid4()
    

    uuid datatypes are available natively in some databases such as Postgresql (SQLAlchemy has a native PG uuid datatype for this purpose - in 0.5 its called sqlalchemy.databases.postgres.PGUuid). You should also be able to store a uuid in any 16 byte CHAR field (though I haven't tried this specifically on MySQL or others).

    0 讨论(0)
  • 2021-02-09 21:06

    Or with ORM mapping:

    import uuid
    from sqlalchemy import Column, Integer, String, Boolean
    
    def uuid_gen():
        return str(uuid.uuid4())
    
    Base = declarative_base()
    class Device(Base):
        id = Column(String, primary_key=True, default=uuid_gen)
    

    This stores it as a string providing better database compatibility. However, you lose the database's ability to more optimally store and use the uuid.

    0 讨论(0)
  • 2021-02-09 21:25

    i use this pattern and it works pretty good. source

    from sqlalchemy import types
    from sqlalchemy.databases.mysql import MSBinary
    from sqlalchemy.schema import Column
    import uuid
    
    
    class UUID(types.TypeDecorator):
        impl = MSBinary
        def __init__(self):
            self.impl.length = 16
            types.TypeDecorator.__init__(self,length=self.impl.length)
    
        def process_bind_param(self,value,dialect=None):
            if value and isinstance(value,uuid.UUID):
                return value.bytes
            elif value and not isinstance(value,uuid.UUID):
                raise ValueError,'value %s is not a valid uuid.UUID' % value
            else:
                return None
    
        def process_result_value(self,value,dialect=None):
            if value:
                return uuid.UUID(bytes=value)
            else:
                return None
    
        def is_mutable(self):
            return False
    
    
    id_column_name = "id"
    
    def id_column():
        import uuid
        return Column(id_column_name,UUID(),primary_key=True,default=uuid.uuid4)
    
    #usage
    my_table = Table('test',metadata,id_column(),Column('parent_id',UUID(),ForeignKey(table_parent.c.id)))
    

    Though zzzeek I believe is the author of sqlalchemy, so if this is wrong he would know, and I would listen to him.

    0 讨论(0)
提交回复
热议问题