简体   繁体   English

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

[英]handling unique constraint for custom field in django admin

Hi I'm new to django and just took my first foray into using a custom field for my model. 嗨,我是django的新手,刚刚第一次尝试使用我的模型的自定义字段。 I have a Char field that I want to always be saved as lower case so I implemented it as a custom field as follows (learned from another Stack Overflow post): 我有一个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

I've tested this out in admin and indeed a field entry gets correctly converted to lowercase before it's saved. 我已在管理员中对此进行了测试,实际上字段条目在保存之前已正确转换为小写。 Unfortunately, when I tested the uniqueness constraint, admin isn't handling the Integrity Error gracefully. 不幸的是,当我测试唯一性约束时,管理员没有优雅地处理完整性错误。 Instead of getting the clean error like I do if it's an exact case match from the get go: 而不是像我一样得到干净的错误,如果它是get get的确切案例匹配:

在此输入图像描述

I get the ugly error page: 我得到了丑陋的错误页面:

在此输入图像描述

How do I go about setting the custom field in such a way that the unique constraint is caught "early" enough to trigger the graceful error, or otherwise modify the admin so that this "later" error is handled more gracefully? 如何以这样的方式设置自定义字段,即“早期”捕获唯一约束以触发正常错误,或以其他方式修改管理员以便更优雅地处理此“稍后”错误?

(Note: I am just using sqlite3 for my db at the moment) (注意:我现在只使用sqlite3作为我的数据库)

UPDATE: In case any one is interested, here's the modified code that worked for me: 更新:如果有人感兴趣,这里是修改后的代码,对我有用:

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

I don't think you'll make it by overriding pre_save , because pre_save gets called after uniqueness validation has occurred. 我认为你不会通过覆盖pre_save实现它,因为在发生唯一性验证后会调用pre_save Try with the other methods, such as get_db_prep_save or get_db_prep_value . 尝试使用其他方法,例如get_db_prep_saveget_db_prep_value

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM