如何在Django模型中创建小写字段? [英] How do you make a lowercase field in a django model?

查看:31
本文介绍了如何在Django模型中创建小写字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用这种方法,我可以将字段另存为小写,但这不能更改现有模型(位于内存中)中的字段.

With this method, I can make a field save as lowercase, but this does not change the field in the existing model (that is in memory).

def get_prep_value(self, value):
    value = super(LowercaseField, self).get_prep_value(value)
    if value is not None:
        value = value.lower()
    return value

我很难弄清楚如何在不覆盖保存并在那里进行更改的情况下将该字段强制转换为小写.但这分裂了此小写字段的逻辑.我想要所有这些在现场.我应该重写什么,以便设置该值强制在内存中强制小写并在数据库中启用小写?

I'm having a hard time figuring out how to force this field to lowercase without overriding save and doing the change there. But that splits the logic for this lowercase field. I'd like all of it in the field. What do I override so that setting this value forces lowercase in memory AND on in the DB?

我不想更改表单,我希望包含在字段类中的所有小写逻辑.

I don't want to change a form, I want all the lowercase logic contained inside the field class.

我发现部分解决方法如下:

I've found a partial work around like so:

def pre_save(self, model_instance, add):
    """ Returns field's value just before saving. """
    attr =  getattr(model_instance, self.attname)
    if attr is not None:
        attr = attr.lower()
        setattr(model_instance, self.attname, attr)
    return attr

def get_prep_value(self, value):
    value = super(LowercaseField, self).get_prep_value(value)
    if value is not None:
        value = value.lower()
    return value

它有点代码味道,并且在保存之前不处理值的检查,但是我看不到如何在不覆盖实际模型类的setattr并在模型类内部处理该值的情况下进行操作本身.

It has a bit of a code smell, and does not handle checking the value before a save, but I don't see how to do that without overriding setattr on the actual model class and catching dealing with that inside the model class itself.

推荐答案

您可以通过在models.py文件中添加以下代码来覆盖Django中的保存"方法

You can override the "save" method in Django by adding the following code in your models.py file

def save(self, *args, **kwargs):
    self.yourfiled = self.yourfield.lower()
    return super(ModelsName, self).save(*args, **kwargs)

当然可以循环处理所有参数.

Of course is possible to handle all params with a loop.

对于所有现有记录,您可以创建一个Management命令,该命令可以将所有字符串转换为小写这里的文档:编写自定义django-admin命令

For all existing record you can create a Management command that can convert all strings to lowercase here the docs: Writing custom django-admin commands

如果您不想更改Save方法,只需将"| lower"标记添加到表单中,即可将UI中的所有字符串都转换为小写

If you don't want to change the Save method, just add to the form the "|lower" tag that will be convert all string to lowercase in UI

{{ value|lower }}

希望获得帮助:)

这篇关于如何在Django模型中创建小写字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆