Skip to main content

ModelMultipleChoiceField

A MultipleChoiceField whose choices are a model QuerySet.

Attributes

AttributeTypeDescription
widgetWidget class = SelectMultipleThe default form widget class used to render the multiple choice selection interface.
hidden_widgetWidget class = MultipleHiddenInputThe widget class used to render the field when the input is hidden.
default_error_messagesdictA dictionary containing localized error messages for invalid lists, invalid choices, and invalid primary key values.

Constructor

Signature

def ModelMultipleChoiceField(
queryset: [QuerySet](../../db/models/query/queryset.md?sid=django_db_models_query_queryset),
**kwargs: dict
)

Parameters

NameTypeDescription
queryset[QuerySet](../../db/models/query/queryset.md?sid=django_db_models_query_queryset)A QuerySet of model objects to be used as choices.
**kwargsdictAdditional keyword arguments passed to the parent class constructor.

Methods


to_python()

@classmethod
def to_python(
value: any
) - > list

Converts the input value into a list of model instances by validating the provided primary keys.

Parameters

NameTypeDescription
valueanyThe raw input data, typically a list of primary keys, to be converted into model instances.

Returns

TypeDescription
listA list of model objects corresponding to the provided primary keys, or an empty list if no value is provided.

clean()

@classmethod
def clean(
value: any
) - > [QuerySet](../../db/models/query/queryset.md?sid=django_db_models_query_queryset)

Validates the input list of values and returns a QuerySet of the corresponding model instances.

Parameters

NameTypeDescription
valueanyThe submitted data to validate, which should be a list or tuple of primary keys.

Returns

TypeDescription
[QuerySet](../../db/models/query/queryset.md?sid=django_db_models_query_queryset)A QuerySet containing the model instances matched by the input values.

prepare_value()

@classmethod
def prepare_value(
value: any
) - > list

Coerces the value into a format suitable for the widget, handling collections of model instances or primary keys.

Parameters

NameTypeDescription
valueanyThe value to prepare, which can be a single object, a QuerySet, or a list of primary keys.

Returns

TypeDescription
listA list of primary keys extracted from the input model instances or raw values.

has_changed()

@classmethod
def has_changed(
initial: any,
data: any
) - > boolean

Determines if the submitted data differs from the initial value by comparing sets of primary keys.

Parameters

NameTypeDescription
initialanyThe original value of the field, used for comparison.
dataanyThe new data submitted via the form to check for changes.

Returns

TypeDescription
booleanTrue if the submitted data represents a different set of objects than the initial data, False otherwise.