gpt4 book ai didi

Django Rest Framework 在一个 api 端点中组合多个查询集

转载 作者:行者123 更新时间:2023-12-02 01:33:09 27 4
gpt4 key购买 nike

如何连接特定模型的列表的输出,其实例由不同字段过滤?例如,我有一个 Places 模型和两个不同的 url。在一个中,显示整个列表,在另一个中仅显示 new_place = True 的实例。使用 django-filter 执行 API。

models.py

class Places(models.Model):
main_photo = models.ImageField(upload_to = 'album/')
place = models.CharField(max_length=100)
new_place = models.BooleanField(default = True)
editor_choice = models.BooleanField(default = False, verbose_name = "Editors choice")
most_popular = models.BooleanField(default = False, verbose_name = "Most popular")

序列化器.py

class PlaceSerializer(ModelSerializer):

url = HyperlinkedIdentityField(
view_name='places_api:detail',
lookup_field='pk'
)
class Meta:
model = Places
fields = (
'url',
'id',
'main_photo',
'name',
'new_place',
'most_popular',
'editor_choice',
)

full_list_views.py

class PlacesListAPIView(ListAPIView):
queryset = Places.objects.all()
serializer_class = PlaceSerializer

new_places_views.py

class PlacesNewListAPIView(ListAPIView):
queryset = Places.objects.all()
serializer_class = PlaceSerializer
filter_backends = (DjangoFilterBackend,)
filter_fields = ('new_place',)

urls.py

url(r'^new/$', views.PlacesNewListAPIView.as_view(), name = 'list_new'),
url(r'^$', views.PlacesListAPIView.as_view(), name = 'place_list'),

这在不同的网址上都运行良好。但是我应该怎么做才能将两个列表都放在一页上。新列表位于页面顶部,完整列表位于页面底部?

最佳答案

你可以做这样的事情。使用QuerySet.union()合并多个查询集。

此示例不支持分页。我怀疑如果您需要分页,您将必须编写自定义分页类。

class MultiFilterPlacesListView(ListAPIView):
"""Custom queryset api view. Does not implement pagination"""

pagination_class = None
queryset = Places.objects.all()
slice_size = 10 # count limit for each of the source queries

def get_queryset(self):
"""Combine queries from new, editor choice and popular"""
new_qs = self.queryset.filter(new_place=True)[:self.slice_size]
editor_qs = self.queryset.filter(editor_choice=True)[:self.slice_size]
popular_qs = self.queryset.filter(popular=True)[:self.slice_size]

return new_qs.union(editor_qs, popular_qs, all=True)

关于Django Rest Framework 在一个 api 端点中组合多个查询集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50238862/

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