I currently have a function inside the method save()
that converts fields of type char to uppercase
class ModeloBase(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
class Meta:
abstract = True
def save(self, *args, **kwargs):
# Obtiene todos los campos de tipo charfield
char_fields = [field.name for field in self._meta.fields if
isinstance(field, models.CharField) and not getattr(field, 'choices')]
for field in char_fields:
valor = getattr(self, field, False)
if valor is not None:
# Elimina los espacios en blanco que no son necesarios
valor = str(valor)
valor = " ".join(valor.split())
# Cambia los caracteres a mayusculas
setattr(self, field, valor.upper())
I want to create a variable in the meta class uppercase_fields = [ ]
so I can indicate specific fields to convert to uppercase.
Just as they are used ordering
, proxy
or others that are already implemented by default.
I solved it in the following way, if someone finds something more optimal I appreciate it
This will be the child class
You can do it in the following way (this way you don't dirty the model so much, I also recommend that the attribute be
uppercase_fields
in uppercase to indicate that it is a constant, besides that in my opinion it looks more elegant and pythonic)On the other hand I don't see the need to create so many methods just to handle an attribute, it's too complicated in my opinion, if you just want to reset the value of the attribute
UPPERCASE_FIELDS
, you can do this:Or get it:
It is much simpler than using several methods to do almost the same thing.
By the way in your solution you mention that "You remove the blanks that are not necessary", as follows:
I don't know if I'm misunderstanding "remove whitespace", but that doesn't actually remove spaces, here's how to do it (I think this is what you were trying to do):
Although you could use
replace()
, which is simpler and faster (which is what I did).And well that would be all, I hope I have helped you.