I’m just getting started in Django development, and I’m trying to dynamically populated a ChoiceField() class with options from a column of DB entries of another model.
This is the way I’m approaching the situation currently:
categories_as_choices = map(lambda x: x.mycolumnname, MyObjectCategory.objects.all())
I’m not really sure if this is the most “pythonic” approach (or the Django equivalent). Does anyone know if there’s a “better” way?
Django provides a field class specifically designed for this: ModelChoiceField.
You’ll need to define
__unicode__method on your category model like this:And then in the form you can simply use