如何在 peewee 模型上添加唯一的不敏感约束?
How to add a unique insensitive constraint on a peewee model?
我想使用带有 sqlite 数据库的 peewee orm 向以下模型添加唯一的不敏感约束
import peewee as p
db = p.SqliteDatabase(':memory:')
class Player(p.Model):
name = p.CharField()
class Meta:
database = db
我想阻止在 table 中添加 'joe' 和 'Joe' 作为玩家名称。由于字段区分大小写,唯一约束是不够的。
谢谢你的想法!
您可以在 Meta.constraints 列表中指定任意约束:
from peewee import *
db = SqliteDatabase(':memory:')
class K(Model):
key = TextField()
class Meta:
constraints = [SQL('UNIQUE ("key" COLLATE NOCASE)')]
database = db
db.create_tables([K])
K.create(key='k1')
K.create(key='K1') # Fails
作为参考,在两个字段上创建不区分大小写的唯一约束的语法为:
class Group(BaseModel):
name = CharField()
category = CharField()
class Meta:
constraints = [SQL('UNIQUE("name" COLLATE NOCASE, "category" COLLATE NOCASE)')]
我想使用带有 sqlite 数据库的 peewee orm 向以下模型添加唯一的不敏感约束
import peewee as p
db = p.SqliteDatabase(':memory:')
class Player(p.Model):
name = p.CharField()
class Meta:
database = db
我想阻止在 table 中添加 'joe' 和 'Joe' 作为玩家名称。由于字段区分大小写,唯一约束是不够的。
谢谢你的想法!
您可以在 Meta.constraints 列表中指定任意约束:
from peewee import *
db = SqliteDatabase(':memory:')
class K(Model):
key = TextField()
class Meta:
constraints = [SQL('UNIQUE ("key" COLLATE NOCASE)')]
database = db
db.create_tables([K])
K.create(key='k1')
K.create(key='K1') # Fails
作为参考,在两个字段上创建不区分大小写的唯一约束的语法为:
class Group(BaseModel):
name = CharField()
category = CharField()
class Meta:
constraints = [SQL('UNIQUE("name" COLLATE NOCASE, "category" COLLATE NOCASE)')]