Can you achieve a case insensitive 'unique' constraint in Sqlite3 (with Django)?

前端 未结 2 1127
离开以前
离开以前 2021-02-08 01:41

So let\'s say I\'m using Python 2.5\'s built-in default sqlite3 and I have a Django model class with the following code:

class SomeEntity(models.Model):
    some         


        
相关标签:
2条回答
  • 2021-02-08 02:25

    Perhaps you can create and use a custom model field; it would be a subclass of CharField but providing a db_type method returning "text collate nocase"

    0 讨论(0)
  • 2021-02-08 02:27

    Yes this can easily be done by adding a unique index to the table with the following command:

    CREATE UNIQUE INDEX uidxName ON mytable (myfield COLLATE NOCASE)

    If you need case insensitivity for nonASCII letters, you will need to register your own COLLATION with commands similar to the following:

    The following example shows a custom collation that sorts “the wrong way”:

    import sqlite3
    
    def collate_reverse(string1, string2):
        return -cmp(string1, string2)
    
    con = sqlite3.connect(":memory:")
    con.create_collation("reverse", collate_reverse)
    
    cur = con.cursor()
    cur.execute("create table test(x)")
    cur.executemany("insert into test(x) values (?)", [("a",), ("b",)])
    cur.execute("select x from test order by x collate reverse")
    for row in cur:
        print row
    con.close()
    

    Additional python documentation for sqlite3 shown here

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