gpt4 book ai didi

python - Django 过滤同一列中的多个值

转载 作者:行者123 更新时间:2023-12-05 06:40:13 25 4
gpt4 key购买 nike

我已经设置了其中一个表名为 Establishment_Type 的列

现在,我正在尝试根据 Establishment_Type 进行过滤。

这是我的 view.py 代码

class ShopDetailAPIView(ListAPIView):
serializer_class = ShopDetailSerializer
def get_queryset(self):
queryset = Shop.objects.all()
type = self.request.query_params.get('type', None)
type2 = self.request.query_params.get('type2', None)
if type is not None and type2 is None:
queryset = queryset.filter(Establishment_Type = type)
elif type is not None and type2 is not None:
queryset = queryset.filter(Q(Establishment_Type = type) | Q(Establishment_Type = type2))
return queryset

在 url 中,我通过键入查询:

http://127.0.0.1:8000/shop/search/?type=Restaurant&type2=Petrol%20Station

只过滤 Establishment_Type = Restaurant 但不过滤 Establishment_Type = Petrol Station

这是我名为 shop 的应用程序中的 urls.py:

urlpatterns = [

url(r'^$', ShopListAPIView.as_view(), name = 'list' ),
#####
url(r'^create/$', ShopCreateAPIView.as_view(), name = 'create' ),
url(r'^search/$', ShopDetailAPIView.as_view(), name = 'detail'),
]

我用于过滤 2 企业类型的 url 是否有误?

我是否需要更改我的代码以过滤 Establishment_Type 列中的 2 个值?

最佳答案

感谢@Thyrst' 建议我使用 Establishment_Type__in=types

我已经以这种方式修改我的代码以使我的过滤器工作

class ShopDetailAPIView(ListAPIView):
serializer_class = ShopDetailSerializer
def get_queryset(self):
queryset = Shop.objects.all()
type = self.request.query_params.get('type', None)
type = type.split(',')
if type is not None:
queryset = queryset.filter(Establishment_Type__in = type)
return queryset

所以类型现在是列表,因此当输入 url 时:

http://127.0.0.1:8000/shop/search/?type=Restaurant,Petrol%20Station

它根据餐厅和加油站进行过滤。

它在仅输入 1 个或多个值时也有效。

目前这很好,但我觉得可能有更好的方法来实现它。

关于python - Django 过滤同一列中的多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43111898/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com