Can I add some arbitrary attributes to django model field?
For example:
charField = models.CharField('char field', max_length=1024, aaaaa=true)
Can I add attribute aaaaa?
Is this doable?
If you check CharField
class CharField(Field):
description = _("String (up to %(max_length)s)")
def __init__(self, *args, **kwargs):
super(CharField, self).__init__(*args, **kwargs)
self.validators.append(validators.MaxLengthValidator(self.max_length))
It accepts **kwargs
but also calls super
and inherited __init__
(Field
object) only accepts named parameters.
class Field(object):
def __init__(self, verbose_name=None, name=None, primary_key=False,
max_length=None, unique=False, blank=False, null=False,
db_index=False, rel=None, default=NOT_PROVIDED, editable=True,
serialize=True, unique_for_date=None, unique_for_month=None,
unique_for_year=None, choices=None, help_text='', db_column=None,
db_tablespace=None, auto_created=False, validators=[],
error_messages=None):
So you can not pass a custom argument.
You must create a custom field
You can assign it as attribute to field object itself:
charField = models.CharField('char field', max_length=1024)
charField.aaaaa = True
Or if you want one liner create a function e.g.:
def extra_attr(field, **kwargs):
for k, v in kwargs.items():
setattr(field, k, v)
return field
and then use:
charField = extra_attr(models.CharField('char field', max_length=1024), aaaaa=True)
If you take a look at /django/db/models/fields/init.py, you can see that such behavior is not intended as Field.init accepts only predefined arguments.
You are, of course, free to write your own custom fields (https://docs.djangoproject.com/en/dev/howto/custom-model-fields/).
Perhaps not the most efficient way but something like this worked for me:
class SpecialCharField(models.CharField):
def __init__(self, *args, **kwargs):
self.aaaaa=kwargs.get('aaaaa',false)
#delete aaaaa from keyword arguments
kwargs = {key: value for key, value in kwargs.items() if key != 'aaaaa'}
super(SpecialCharField,self).__init__(*args, **kwargs)
class ModelXY(models.Model):
charField = SpecialCharField('char field', max_length=1024, aaaaa=true)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With