Django Rest框架过滤器 [英] django rest framework filter

查看:89
本文介绍了Django Rest框架过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用由Django rest框架制成的API,
我正在尝试过滤JSON
这是我的 serializers.py 文件

I'm working with API made from Django rest framework, I am trying to make a filter to a JSON This is my serializers.py file

from rest_framework import serializers
from .models import Establecimiento,Categoria,Ciudad,Zona
import django_filters

class EstablecimientoSerializer(serializers.ModelSerializer):
    class Meta:
        model = Establecimiento
        depth = 1

        fields =  ('nombre',
                   'ciudad',
                   'categoria',
                   'direccion',
                   'telefono',
                   'precioMinimo',
                   'precioMaximo',)

和这是我的 views.py 文件

from rest_framework import viewsets
from .serializers import EstablecimientoSerializer, CategoriaSerializer
from models import *
from rest_framework import filters
from rest_framework import generics

class EstablecimientoViewSet(viewsets.ModelViewSet):
    queryset = Establecimiento.objects.all()
    serializer_class = EstablecimientoSerializer
    filter_fields = ('categoria',)

然后在 EstablecimientoViewSet 类,我将 filter_fields =('categoria',)
过滤为带有类别字段的网址的API

Then in the EstablecimientoViewSet class, I put a filter_fields = ('categoria',) to filter the url's API with the category field

如果将过滤器添加到查询参数,结果集不会更改,它会显示所有未过滤的数据。

If I add the filter to the query parameters, the result set does not change, it shows all data unfiltered.

...establecimiento?establecimiento=bar

如何对该型号进行此过滤?

How can I make this filter about this model?

推荐答案

您需要定义过滤器后端和所有计划过滤的相关字段:

You need to define filter backend and all related fields you're planning to filter on:

class EstablecimientoViewSet(viewsets.ModelViewSet):
    filter_backends = (filters.DjangoFilterBackend,)
    filter_fields = ('categoria', 'categoria__titulo',)

示例:

URL?categoria__titulo=Categoria 1

这篇关于Django Rest框架过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆