Open
Description
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
Labels
No labels