gpt4 book ai didi

python - 在 django admin 中处理自定义字段的唯一约束

转载 作者:行者123 更新时间:2023-11-28 19:17:59 27 4
gpt4 key购买 nike

您好,我是 Django 的新手,刚刚开始尝试为我的模型使用自定义字段。我有一个 Char 字段,我希望始终将其保存为小写字母,因此我将其实现为自定义字段,如下所示(从另一篇 Stack Overflow 帖子中学习):

from django.db import models
from django.db.models.fields import CharField

class LowercaseCharField(CharField):
def pre_save(self, model_instance, add):
current_value = getattr(model_instance, self.attname)
setattr(model_instance, self.attname, current_value.lower())
return getattr(model_instance, self.attname)


class Item(models.Model):
name = LowercaseCharField(max_length=50, unique=True)

def __str__(self):
return self.name

我已经在管理员中对此进行了测试,确实一个字段条目在保存之前被正确转换为小写。不幸的是,当我测试唯一性约束时,管理员没有优雅地处理完整性错误。如果从一开始就完全匹配大小写,而不是像我那样得到干净的错误:

enter image description here

我得到丑陋的错误页面:

enter image description here

我如何设置自定义字段,以便“及早”捕获唯一约束以触发优雅错误,或者修改管理以便更优雅地处理此“稍后”错误?

(注意:目前我的数据库只使用 sqlite3)

更新:如果有人感兴趣,这里是对我有用的修改后的代码:

class LowercaseCharField(CharField):
def get_db_prep_value(self, value, connection, prepared=False):
return value.lower()

最佳答案

我认为您不会通过覆盖 pre_save 来实现它,因为 pre_save 在唯一性验证发生后被调用。尝试使用其他方法,例如 get_db_prep_saveget_db_prep_value

关于python - 在 django admin 中处理自定义字段的唯一约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31168331/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com