How to create a custom related model field?

82 views Asked by At

I created a new field inheriting from OneToOneField::

class MeasureField(models.OneToOneField):
    """ A custom Django model Field for Measure """

    __metaclass__ = models.SubfieldBase

    description = _("Measurement")

    def __init__(self, *args, **kwargs):
        self.measure_types = args
        args = (Measure,)
        if 'to' in kwargs.keys():
            args = tuple()
        super(MeasureField, self).__init__(*args, **kwargs)

    def deconstruct(self):
        name, path, args, kwargs = super(MeasureField, self).deconstruct()
        args = self.measure_types
        return name, path, args, kwargs

It just takes a list arguments (args) and is always related to the model Measure. But when I try to put it on a model and to create one :

basic_condition = MeasureField(
    'Density',
    related_name="basic_condition_of_product",
)

I have the following error:

AttributeError: 'Product' object has no attribute 'basic_condition_id'

I know that related field add an attribute with _id appended for the database. But I don't know why my custom field doesn't do it.

How am I supposed to create it ?

1

There are 1 answers

0
Gagaro On

I actually shouldn't have added the metaclass SubfieldBase. It works fine without it.