Adding custom attributes to django model field

夙愿已清 提交于 2021-02-08 13:33:27

问题


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?


回答1:


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




回答2:


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)



回答3:


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




回答4:


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)



回答5:


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.



来源:https://stackoverflow.com/questions/20679057/adding-custom-attributes-to-django-model-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!