Skip to content

Schema generation with django-filter ModelMultipleChoiceFilter and to_field_name in 0.29.0 #1475

Description

@glennmatthews

Describe the bug

When using a django-filter ModelMultipleChoiceFilter with a non-primary-key to_field_name, schema generation in 0.29.0 logs a warning that was not seen in previous versions:

    # works, no warning in schema generation
    groups_id = ModelMultipleChoiceFilter(
        field_name="groups",
        queryset=Group.objects.all(),
        label="Group (ID)",
    )
    # works, but logs a warning in schema generation under 0.29.0 - see below
    groups = ModelMultipleChoiceFilter(
        field_name="groups__name",
        queryset=Group.objects.all(),
        to_field_name="name",
        label="Group (name)",
    )
Unable to guess choice types from values, filter method's type hint or find "groups" in model. Defaulting to string.

This appears to be a regression introduced by #1446. Changing the filter definition as follows makes drf-spectacular happy but breaks the operation of the filter:

    groups = ModelMultipleChoiceFilter(
        field_name="groups",  # <------<< removed "__name"
        queryset=Group.objects.all(),
        to_field_name="name",
        label="Group (name)",
    )
ValueError: Field 'id' expected a number but got 'Group 1'.

I believe this is related to an inconsistency in django-filter about how ModelMultipleChoiceFilter behaves when to_field_name is the PK field of the related model, versus when it is not the PK.

See also: carltongibson/django-filter#1661 (comment)

To Reproduce

Expected behavior

Schema generation needs to work correctly and log no warnings with correctly constructed django-filter ModelMultipleChoiceFilter filters, both when to_field_name is the PK field of the related model and when it is not the PK field.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions