0

I want to over-write a field in a child model.

My base model

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

Now I subclass this model in other model

class Product(AbstractProduct):
    ....
    structure = models.CharField(
        _("Product structure"), max_length=10, choices=STRUCTURE_CHOICES2,
        default=STANDALONE)

Error I get:

    django.core.exceptions.FieldError: Local field 'structure' 
    in class 'Product' clashes with field of similar name 
from base class 'AbstractProduct'

This answer says it's NOT possible. But seems like an old post. Also tried put in it def __init__ as one of the answers mentioned, but still no avail. Is there any workaround this or still not possible ?

Community
  • 1
  • 1
Coderaemon
  • 3,619
  • 6
  • 27
  • 50
  • Check this http://stackoverflow.com/questions/6377631/how-to-override-the-default-value-of-a-model-field-from-an-abstract-base-class – wolendranh Sep 09 '15 at 11:28
  • It does seem to be impossible. As silly as it sounds, Django will not let you override fields even from abstract bases. You could alter the choices of the existing field programmatically though. – patrys Sep 09 '15 at 11:30
  • how to alter programmatically ? I tried `Product._meta.get_field('structure').choices = STRUCTURE_CHOICES2` . Error: `AttributeError: can't set attribute` – Coderaemon Sep 09 '15 at 11:36
  • If I'm not mistaken, django doesn't enforce the choices on a database level... can you not just override `Structure_Choices`? (It doesn't look like you care about overriding the field, just the choices available) – Sayse Sep 09 '15 at 11:38
  • I can but I don't want to touch the abstract model as it is inside a framework(django-oscar). On upgrade that will be gone. – Coderaemon Sep 09 '15 at 11:41
  • Hmm.. thats the only option I can think of I'm afraid, you can't override a field. But since the choices aren't checked for database validation you would have just been able to override the choices field I'd imagine (even that might have been tricky) – Sayse Sep 09 '15 at 11:43

0 Answers0