Skip to content

filterset_fields not working with ContentType and SlugRelatedField #9726

Open
@Ivanca

Description

@Ivanca

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

models.py

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

serializers.py

from django.contrib.contenttypes.models import ContentType
from rest_framework import serializers
from .models import Foo

class FooSerializer(serializers.ModelSerializer):
    class Meta:
       model = Foo

    content_type = serializers.SlugRelatedField(
        queryset=ContentType.objects.all(),
        slug_field='model',
    )

views.py

class FooViewSet(viewsets.ModelViewSet):
    queryset = Foo.objects.all()
    serializer_class = serializers.FooSerializer
    filterset_fields = ['content_type']

The expectation is to be able to filter by doing content_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:

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

    class Meta:
        model = Foo
        fields = (
            '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