Django过滤器错误:“ meta”不能包含非模型字段名

icnyk63a  于 2023-01-27  发布在  Go
关注(0)|答案(3)|浏览(447)

我正在使用Django REST框架和django-filters,我想使用反向关系annotation_set作为GET API的一个过滤器,该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)

序列化器为:

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

    class Meta:
        model = Detection
        fields = '__all__'

视图集为:

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))

当我调用端点时,我得到错误:

'Meta.fields' must not contain non-model field names: annotation_set__id

字段不应该存在吗?注意:我尝试向Annotation模型添加其他字段,然后使用annotation_set__newfield,但仍然出现错误。我可以确认newfield存在,因为当我注解掉设置filterset_fields的行时,它被正确序列化并由API返回。

bfrts1fy

bfrts1fy1#

查看django filter文档时,您可能遗漏了一个DjangoFilterBackend的引用,例如

queryset = Detection.objects.all()
serializer_class = DetectionSerializer
filter_backends = (filters.DjangoFilterBackend,)
filterset_fields = ('annotation_set__id', )

(see:https://django-filter.readthedocs.io/en/stable/guide/rest_framework.html

ycl3bljg

ycl3bljg2#

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

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

如果有人知道原因,我很想知道!谢谢!

u7up0aaq

u7up0aaq3#

试试这个,我有类似的问题,它为我工作。在您的视图文件中更改filterset_fields如下。

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

相关问题