Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Same field, different choices in Django model subclasses

Is it possible to use different choices for subclasses of models? The following code should give you an idea

class Clothing(models.Model):
    size = models.CharField(max_length=1)
    colour = models.CharField(max_length=1)

SHIRT_SIZES = {
    'S','Small',
    'M','Medium',
    'L','Large',
}

class TShirt(models.Model):
    size = models.CharField(max_length=1, choices=SHIRT_SIZES)

MENS_CHOICES = {
    'K','Black',
    'R','Red',
    'B','Blue',
}

class MensColours(models.Model):
    colour = models.CharField(max_length=1, choices=MENS_CHOICES)

class MensShirt(MensColours, TShirt):
    class Meta:
        verbose_name = "men's shirt"

WOMENS_CHOICES = {
    'P','Pink',
    'W','White',
    'B','Brown',
}

class WomensColours(models.Model):
    colour = models.CharField(max_length=1, choices=WOMENS_CHOICES)

class WomensShirt(WomensColours, TShirt):
    class Meta:
        verbose_name = "women's shirt"

The reason I'm using mixins is that I have attributes/choices that can be shared between different models (e.g. also having women's/men's pants, which may have the same colour choices but different size choices than the TShirts). Overall, however, all clothing has a colour and a size.

How should I do this?

like image 429
Lexo Avatar asked May 06 '11 12:05

Lexo


1 Answers

No. Potential field choices are fixed in the parent. You can get around this in a form by specifying the valid choices for the form field, but you cannot change the fundamental nature of the model field.

like image 80
Ignacio Vazquez-Abrams Avatar answered Oct 27 '22 00:10

Ignacio Vazquez-Abrams