Home > database >  DRF - Data not getting filtered with django-filters
DRF - Data not getting filtered with django-filters

Time:06-03

FilterSet:

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

List function:

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)

View:

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)

Model:

   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"

The response from view is not getting filtered by the parameters, it is retrieving all the records from the db.

CodePudding user response:

use model = Field instead of meta = Field in your filterset class and in your APIVIEW mention your filter

class FieldList(ApiAuthMixin, APIView):
    filterset_class = FieldFilter
  • Related