Home > Mobile >  Change choices list in child model Django
Change choices list in child model Django

Time:10-14

I have a model that is being inherited by another one and has a field that has choices. Is there any way I can change the choices options, or append a new item to choices on the inherited model level?

app1

class ModelA(PolymorphicModel):
    choice1 = "choice1"
    choice2 = "choice2"
    CHOICES = (
        (choice1, "Choice 1"),
        (choice2, "Choice 2"),
    )
    
    method = models.CharField(max_length=30, choices=CHOICES)

app2

from app1.models import ModelA  
class ModelB(ModelA):
    # In this model, I have to exclusively add `choice3` to choices.

CodePudding user response:

Define the choice constant out side of your class and then use the constant accordingly like :-

choice1 = "choice1"
choice2 = "choice2"
CHOICES = (
        (choice1, "Choice 1"),
        (choice2, "Choice 2"),
    )

class ModelA(PolymorphicModel):
    method = models.CharField(max_length=30, choices=CHOICES)

class ModelB(ModelA)
    choice3 = "choice3"
    CHOICES   = ((choice3, "Choice 3"),)

    method = models.CharField(max_length=30, choices=CHOICES)
  • Related