Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python SQLAlchemy中不区分大小写的字符串列?_Python_Sqlalchemy - Fatal编程技术网

Python SQLAlchemy中不区分大小写的字符串列?

Python SQLAlchemy中不区分大小写的字符串列?,python,sqlalchemy,Python,Sqlalchemy,我可以在sqlalchemy中创建不区分大小写的字符串列吗?我正在使用sqlite,可能通过更改排序规则通过DB来实现,但我想将其保留在sqlalchemy/python中。sqlite允许在文本字段中使用: SQLite version 3.6.22 sqlite> create table me (name text collate nocase); sqlite> .schema CREATE TABLE me (name text collate nocase); sqlit

我可以在sqlalchemy中创建不区分大小写的字符串列吗?我正在使用sqlite,可能通过更改排序规则通过DB来实现,但我想将其保留在sqlalchemy/python中。

sqlite允许在文本字段中使用:

SQLite version 3.6.22
sqlite> create table me (name text collate nocase);
sqlite> .schema
CREATE TABLE me (name text collate nocase);
sqlite> insert into me values("Bob");
sqlite> insert into me values("alice");
sqlite> select * from me order by name;
alice
Bob

SQLalchemy在模式上有一个操作符,但我不确定何时应用它。

SQLalchemy在默认情况下似乎不允许在表创建(DDL)阶段使用COLLATE子句,但我最终找到了一种在SQLalchemy 0.6+上实现这一点的方法。不幸的是,它涉及到一些子类化和装饰,但它相当紧凑

from sqlalchemy import *
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.types import TypeDecorator

class CI_String(TypeDecorator): 
  """ Case-insensitive String subclass definition"""
  impl = String 
  def __init__(self, length, **kwargs):
      if kwargs.get('collate'):
          if kwargs['collate'].upper() not in ['BINARY','NOCASE','RTRIM']:
              raise TypeError("%s is not a valid SQLite collation" % kwargs['collate'])
          self.collation = kwargs.pop('collate').upper()
      super(CI_String, self).__init__(length=length, **kwargs)

@compiles(CI_String, 'sqlite')
def compile_ci_string(element, compiler, **kwargs):
  base_visit = compiler.visit_string(element, **kwargs) 
  if element.collation:
      return "%s COLLATE %s" % (base_visit, element.collation) 
  else:
      return base_visit
然后,新的字符串类型可以正常用于创建表:

just_a_table = Table('table_name', metadata,
               Column('case_insensitive', CI_String(8, collate='NOCASE'), nullable=False))

希望有人觉得这个有用

在SQLAlchemy 0.8中,他们向所有字符串类型添加了排序规则参数。COLLATE关键字现在由几个数据库后端支持,包括MySQL、SQLite和Postgresql。你应该能够写这样的东西:

my_table = Table('table_name', meta,
                 Column('my_column', String(255, collation='NOCASE'),
                 nullable=False))