Django 过滤器错误:“Meta.fields”不得包含非模型字段名称

use*_*621 5 python django filter django-filter django-rest-framework

我正在使用 Django REST 框架和 django-filters,并且我想使用反向关系annotation_set作为GET使用 model 的 API 的过滤器之一Detection。型号如下:

class Detection(models.Model):
    image = models.ImageField(upload_to="detections/images")

    def local_image_path(self):
        return os.path.join('images' f"{self.id}.jpg")


class Annotation(models.Model):
    detection = models.ForeignKey(Detection, on_delete=models.CASCADE)
    attribute = models.CharField(max_length=255)
Run Code Online (Sandbox Code Playgroud)

序列化器是:

class DetectionSerializer(UniqueFieldsMixin, serializers.ModelSerializer):
    local_image_path = serializers.CharField()

    class Meta:
        model = Detection
        fields = '__all__'

Run Code Online (Sandbox Code Playgroud)

视图集是:


class DetectionTrainingViewSet(
        mixins.ListModelMixin,
        mixins.RetrieveModelMixin,
        viewsets.GenericViewSet
    ):
    queryset = Detection.objects.all()
    serializer_class = DetectionSerializer
    filterset_fields = ('annotation_set__id', )

    @action(methods=['GET'], detail=False)
    def list_ids(self, request):
        queryset = self.get_queryset()
        filtered_queryset = self.filter_queryset(queryset)
        return Response(filtered_queryset.values_list('id', flat=True))
Run Code Online (Sandbox Code Playgroud)

当我调用端点时,出现错误:

'Meta.fields' must not contain non-model field names: annotation_set__id
Run Code Online (Sandbox Code Playgroud)

这个领域不应该存在吗?注意:我尝试将其他字段添加到模型中Annotation然后使用,annotation_set__newfield但仍然有错误。我可以确认该newfield存在,因为当我注释掉设置filterset_fields.

use*_*621 2

显然我必须明确说明反向关系的名称:

class Annotation(models.Model):
    detection = models.ForeignKey(Detection, on_delete=models.CASCADE, related_name='annotation_set')
    attribute = models.CharField(max_length=255)
Run Code Online (Sandbox Code Playgroud)

如果有人知道为什么,我很想知道!谢谢!