DRF - 数据没有被 django-filters 过滤

DRF - Data not getting filtered with django-filters

过滤器集:

class FieldFilter(django_filters.FilterSet):
    class Meta:
        meta = Field
        fields = ("table__id","type")

列表函数:

def field_list(*, filters=None):
    filters = filters or {}
    qs = Field.objects.all()
    return FieldFilter(filters, qs).qs

FilterSerializer:

class FieldFilterSerializer(serializers.Serializer):
    table__id = serializers.IntegerField(required=False)
    type = serializers.CharField(required=False)

查看:

class FieldList(ApiAuthMixin, APIView):
    perm_slug = f"{Field._meta.app_label}.{Field._meta.object_name}"

    def get(self, request):
        field_filter_serializer = FieldFilterSerializer(data=request.query_params)
        field_filter_serializer.is_valid(raise_exception=True)
        fields = field_list(filters=field_filter_serializer.validated_data)
        serializer = FieldSerializer(fields, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)

型号:

   class Field(BaseModel):
        """
        Model for Fields.
        """
    
        id = models.AutoField(primary_key=True)
        name = models.CharField(max_length=255)
        type = models.CharField(max_length=255)  # metric or dimension
        display_name = models.CharField(max_length=255, null=True, blank=True)
        table = models.ForeignKey(
            Table, db_column="table_id", on_delete=models.CASCADE
        )
        from_table_column = models.BooleanField(default=True)
    
        class Meta:
            db_table = "fields"
            verbose_name_plural = "fields"

来自视图的响应没有被参数过滤,它正在从数据库中检索所有记录。

在您的过滤器集中使用 model = Field 而不是 meta = Field class 并在您的 APIVIEW 中提及您的过滤器

class FieldList(ApiAuthMixin, APIView):
    filterset_class = FieldFilter