Modify the variable of abstract_class(models.model)

34 Views Asked by At

I want to modify the STRUCTURE_CHOICES so that it can reflect into structure field choices.

class AbstractProduct(models.Model):

...

  STRUCTURE_CHOICES = (
      (STANDALONE, _('Stand-alone product')),
      (PARENT, _('Parent product')),
      (CHILD, _('Child product'))
  )

...

  structure = models.CharField(
      _("Product structure"), max_length=10, choices=STRUCTURE_CHOICES,
      default=STANDALONE)

...

class Product(AbstractProduct):

...

  STRUCTURE_CHOICES = (
    (STANDALONE, _('Stand-alone product')),
    (PARENT, _('Parent product')),
    (CHILD, _('Child product')),
    (NEW_CHOICE, _('New Choice'))
  )

...

I tried doing it in this way but it did not work:

class Product(AbstractProduct): ...

  def __init__(self, *args, **kwargs):

     self.STRUCTURE_CHOICES = (
        (STANDALONE, _('Stand-alone product')),
        (PARENT, _('Parent product')),
        (CHILD, _('Child product')),
        (NEW_CHOICE, _('New Choice'))
     )
     return super(Product, self).__init__(*args, **kwargs)

...

1

There are 1 best solutions below

0
On

The choices are assigned to the field at definition, not at run-time. Overriding the STRUCTURE_CHOICES attribute will not affect the field in any way. What you can do however is modify the choices of an existing field:

class Product(AbstractProduct):
    pass

structure_field = Product._meta.get_field('structure')
structure_field.choices = …