python 如何获取字符串列的sqlalchemy长度

hivapdat  于 2022-12-02  发布在  Python
关注(0)|答案(4)|浏览(159)

考虑下面这个简单的表定义(使用SQLAlchemy-0.5.6)

from sqlalchemy import *

db = create_engine('sqlite:///tutorial.db')

db.echo = False  # Try changing this to True and see what happens

metadata = MetaData(db)

user = Table('user', metadata,
    Column('user_id', Integer, primary_key=True),
    Column('name', String(40)),
    Column('age', Integer),
    Column('password', String),
)

from sqlalchemy.ext.declarative import declarative_base

class User(declarative_base()):

    __tablename__ = 'user'
    user_id = Column('user_id', Integer, primary_key=True)
    name = Column('name', String(40))

我想知道列名称的最大长度是多少,例如,从用户表和从用户(声明类)

print user.name.length
print User.name.length

我尝试过(User.name.type.length),但它抛出异常

Traceback (most recent call last):
  File "del.py", line 25, in <module>
    print User.name.type.length
  File "/usr/lib/python2.5/site-packages/SQLAlchemy-0.5.6-py2.5.egg/sqlalchemy/orm/attributes.py", line 135, in __getattr__
    key)
AttributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' object has an attribute 'type'
omhiaaxx

omhiaaxx1#

User.name.property.columns[0].type.length

注意,SQLAlchemy支持复合属性,这就是为什么columns是一个列表。它有一个简单的列属性项。

zvokhttg

zvokhttg2#

这应该可以工作(在我的机器上测试):

print user.columns.name.type.length
91zkwejq

91zkwejq3#

当字段太大时,我会遇到错误,所以我写了一个通用函数来修剪任何字符串,并考虑到带有空格的单词。这将保持单词不变,并修剪字符串以供插入。我包括了我的orm模型以供参考。

class ProductIdentifierTypes(Base):
    __tablename__ = 'prod_id_type'
    id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String(length=20))
    description = Column(String(length=100))

def trim_for_insert(field_obj, in_str) -> str:

    max_len = field_obj.property.columns[0].type.length
    if len(in_str) <= max_len:
        return in_str
    
    logger.debug(f'Trimming {field_obj} to {max_len} max length.')
    
    trim_str = in_str[:(max_len-1)]
    
    if ' ' in trim_str[:int(max_len*0.9)]:
        return(str.join(' ', trim_str.split(' ')[:-1]))
    
    return trim_str

def foo_bar():
    from models.deals import ProductIdentifierTypes, ProductName
    
    _str = "Foo is a 42 year old big brown dog that all the kids call bar."
    
    print(_str)
    
    print(trim_for_insert(ProductIdentifierTypes.name, _str))
    
    _str = "Full circle from the tomb of the womb to the womb of the tomb we come, an ambiguous, enigmatical incursion into a world of solid matter that is soon to melt from us like the substance of a dream."
    
    print(_str)
    
    print(trim_for_insert(ProductIdentifierTypes.description, _str))```
v1uwarro

v1uwarro4#

如果您有权访问该类:

TableClass.column_name.type.length

如果您可以存取执行严修,请使用__class__ dunder方法来存取Class。

table_instance.__class__.column_name.type.length

因此,在您的情况下:

# Via Instance
user.__class__.name.type.length
# Via Class
User.name.type.length

我的用例类似于@Gregg威廉姆森,但是,我以不同的方式实现了它:

def __setattr__(self, attr, value):
    column = self.__class__.type
    if length := getattr(column, "length", 0):
        value = value[:length]
    super().__setattr__(name, value)

相关问题