Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork7k
Open
Description
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
Labels
No labels