pythondjangomodelchoicefield

Django Model Choice Field How to return the primary key of the object instead of the display value


I am trying to use the modelchoicefield that Django provides; however, it is not behaving the way I expected.

I want the display to the end user to be a string value from my model (which works), but return a the primary key of the Model when the user submits the form (not the display value). I attempted to use the to_field_name="id" on the Django form and it does render the values correctly when the HTML is rendered, but when the user submits the form the value I get back is the display value, not the primary key I am expecting.

customer_edit_form.py

annual_income = forms.ModelChoiceField(label='Annual income', to_field_name="id", queryset=cust_income_range.objects.all(), empty_label='-- None --')

models.py

# Annual Income Model
class cust_income_range(models.Model):
    id = models.IntegerField(primary_key=True)
    range = models.CharField(max_length=50)

    def __str__(self):
        return self.range

customer_view.py

annual_income = form.cleaned_data['annual_income']

Solution

  • After a lot of troubleshooing, I discovered that you can do something like this in the view to get the ID value instead of the str value.

    annual_income = form.cleaned_data['annual_income'].pk