Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

filterset_fields not working with ContentType and SlugRelatedField #9726

Open
@Ivanca

Description

@Ivanca

UsingSlugRelatedField(queryset=ContentType.objects.all(), slug_field='model',) used to work but doesn't anymore

models.py

classFoo(models.Model):product_type=models.ForeignKey(ContentType,on_delete=models.CASCADE,    )

serializers.py

fromdjango.contrib.contenttypes.modelsimportContentTypefromrest_frameworkimportserializersfrom .modelsimportFooclassFooSerializer(serializers.ModelSerializer):classMeta:model=Foocontent_type=serializers.SlugRelatedField(queryset=ContentType.objects.all(),slug_field='model',    )

views.py

classFooViewSet(viewsets.ModelViewSet):queryset=Foo.objects.all()serializer_class=serializers.FooSerializerfilterset_fields= ['content_type']

The expectation is to be able to filter by doingcontent_type=user but instead it throws the following error:
Select a valid choice. That choice is not one of the available choices, which doesn't make sense, especially since printing the choices show that "user" is the "model" attribute of one of them.

One possible workaround is to create a custom FilterSet class, but it doesn't do anything special to fix it, just a blank filter with the same references used at SlugRelatedField before, so its clear its redundant and drf should work without it:

classContentTypeFilterSet(django_filters.FilterSet):content_type=django_filters.ModelChoiceFilter(field_name='content_type',queryset=ContentType.objects.all(),to_field_name='model',label='Model'    )classMeta:model=Foofields= ('content_type',        )

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions


      [8]ページ先頭

      ©2009-2025 Movatter.jp