Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding custom attributes to django model field

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?

like image 751
milandjukic88 Avatar asked Dec 19 '13 10:12

milandjukic88


4 Answers

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

like image 103
FallenAngel Avatar answered Oct 09 '22 14:10

FallenAngel


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)
like image 34
icaine Avatar answered Oct 09 '22 14:10

icaine


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/).

like image 33
Lyudmil Nenov Avatar answered Oct 09 '22 14:10

Lyudmil Nenov


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)
like image 29
sir_dance_a_lot Avatar answered Oct 09 '22 13:10

sir_dance_a_lot