About Model Choice Fields

By default, django.forms.ModelChoiceField uses the __str__() method of the model to represent the items in the option list.

When your __str__() representations are not unique, you can extend the ModelChoiceField and overwrite the label_from_instance(self, obj) method and display custom unique options:

1
2
3
4
5
from django.forms import ModelChoiceField

class ModelChoiceFieldWithIDs(ModelChoiceField):
    def label_from_instance(self, obj):
        return f"{obj.title} (ID={obj.pk})"

Tips and Tricks Programming User Experience Django 4.2 Django 3.2 Django 2.2 Python 3