Skip to main content

ModelChoiceIterator

This class provides an iterator for model-based form fields, transforming a database queryset into a sequence of choice tuples. It handles the inclusion of optional empty labels and optimizes memory usage by leveraging database iterators when prefetching is not required. The class also implements standard collection interfaces to support length checks and boolean evaluations based on the underlying data.

Attributes

AttributeTypeDescription
field[ModelChoiceField](modelchoicefield.md?sid=django_forms_models_modelchoicefield)The ModelChoiceField instance associated with this iterator, used to access configuration like empty labels and value preparation.
queryset[QuerySet](../../db/models/query/queryset.md?sid=django_db_models_query_queryset)The database QuerySet used to fetch the model instances that will be transformed into selectable choices.

Constructor

Signature

def ModelChoiceIterator(
field: [ModelChoiceField](modelchoicefield.md?sid=django_forms_models_modelchoicefield)
)

Parameters

NameTypeDescription
field[ModelChoiceField](modelchoicefield.md?sid=django_forms_models_modelchoicefield)The field instance containing the queryset and configuration for choices.

Methods


choice()

@classmethod
def choice(
obj: [Model](../../db/models/base/model.md?sid=django_db_models_base_model)
) - > tuple

Constructs a choice tuple for a specific model instance, containing a specialized value object and the display label.

Parameters

NameTypeDescription
obj[Model](../../db/models/base/model.md?sid=django_db_models_base_model)The model instance to be converted into a choice option

Returns

TypeDescription
tupleA tuple consisting of a ModelChoiceIteratorValue and the string label derived from the instance.