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?
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/).
This worked for me:
class SpecialCharField(models.CharField):
def __init__(self, *args, **kwargs):
self.aaaaa=kwargs.pop('aaaaa',false)
super(SpecialCharField,self).__init__(*args, **kwargs)
class ModelXY(models.Model):
charField = SpecialCharField('char field', max_length=1024, aaaaa=true)
kwargs.pop('aaaaa') instead of retrieving with .get and then creating a new kwargs object.You failed to mention what you want this attribute to actually do.
Generally speaking, if you're trying to customize the CharField behavior, and it's not something CharField provides out-of-the-box, you'll need to create your own CustomCharField that extends models.CharField and implements the behavior you're expecting from aaaaaaa=True.