Search code examples
pythondjangomodels

How to map values of a Django model column to a list?


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?


Solution

  • Django provides a field class specifically designed for this: ModelChoiceField.

    You'll need to define __unicode__ method on your category model like this:

    def __unicode__(self):
        return self.mycolumnname
    

    And then in the form you can simply use

    category = forms.ModelChoiceField(queryset=MyObjectCategory.objects.all())