【问题标题】:How to add a unique insensitive constraint on a peewee model?如何在 peewee 模型上添加唯一的不敏感约束?
【发布时间】:2021-06-04 03:13:28
【问题描述】:

我想使用 peewee orm 和 sqlite 数据库为以下模型添加一个唯一的不敏感约束

import peewee as p

db = p.SqliteDatabase(':memory:')

class Player(p.Model):
   name = p.CharField()
  
   class Meta:
      database = db

我想防止在表格中添加“joe”和“Joe”作为玩家姓名。由于该字段区分大小写,因此唯一的约束是不够的。

感谢您的想法!

【问题讨论】:

标签: sqlite peewee


【解决方案1】:

您可以在 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

【讨论】:

  • 这段代码按我的预期工作。谢谢!
【解决方案2】:

作为参考,在两个字段上创建不区分大小写的唯一约束的语法为:

class Group(BaseModel):
    name = CharField()
    category = CharField()

    class Meta:
        constraints = [SQL('UNIQUE("name" COLLATE NOCASE, "category" COLLATE NOCASE)')]

【讨论】:

    猜你喜欢
    • 2013-05-04
    • 1970-01-01
    • 1970-01-01
    • 2021-04-01
    • 1970-01-01
    • 2017-11-30
    • 1970-01-01
    • 2022-01-01
    • 1970-01-01
    相关资源
    最近更新 更多