List Choices coming from a model data

Hi,

First sorry for my english, I am a french girl :frowning:

In one of my models, I am using a choice list as follow :
class Color(models.Model):
CHOICES_COLOR = (
(‘Red’, ‘Red’),
(‘Blue’, ‘Blue’),
(‘Black’, ‘Black’),
)
my_color = models.CharField(max_length = 50, choices = CHOICES_COLOR)

Is it possible to have this kind of choice list but link to an other models ?
For example :
class Color_Name(models.Model):
name = models.CharField(max_length = 50)

class Color(models.Model):
my_color = models.CharField(max_length = 50, choices = Color_Name)

The goal is to let the user set the choice list data and not put it in “hard mode” in the code

Thanks for your help

Thais

Please, there’s never a need to apologize here. Your English is far better than my French - we appreciate you making the effort.

Yes! One option is the technique we use. Rather than making my_color a CharField, make it a ForeignKey.

Example:

# Note - The line above this is ``` to maintain formatting.
class Color(Model):
    my_color = ForeignKey(ColorName, ...)

class ColorName(Model):
   color_code = CharField(max_length=50, primary_key=True)
   color_name = CharField(max_length=50)

    def __str__(self):
        return color_name

# The line after this is ``` to close this block of code

By default, Django renders a ForeignKey field as a select list with the string representation of the field.
For us, this has the advantage of being able to assign additional attributes to those choices for use elsewhere in the system. For example, you could add another column for the color code, and then be able to directly get the code from the selected choice.

Another option is to use a queryset to create the list of 2-tuples for the choices. For example, assume the ColorName class I defined earlier. You could set the choices to:
ColorName.objects.all().values_list('color_code', 'color_name')

Wouah thanks a lot for your help Ken.
I try it and it works find, exactly what I needed :slight_smile:

Thanks so much for your help

I an starting with Django, so I think I will repost a question in this forum soon ;-))))

Thais