如何更新ListModelMixin中的列表?

时间:2017-02-23 20:01:17

标签: django python-3.x django-rest-framework

我正在使用django rest框架来构建后端。我已经定义了我的模型:

class TV(models.Model):
    brand = models.CharField(max_length=100, null=True)
    price = models.DecimalField(max_digits=10, decimal_places=2)

我定义了我的观点

class TVViewSet(viewsets.ModelViewSet, ListModelMixin):
    serializer_class = TVSerializer
    filter_backends = (filters.DjangoFilterBackend, filters.OrderingFilter,)
    filter_class = TVFilter
    ordering_fields =  ["num_stores","stores__price",]
    ordering = ("-num_stores",)

    def get_queryset(self):
        queryset = TV.objects.annotate(num_stores=Count('stores')).order_by('-num_stores')
        if self.request.GET.get("search"):
            selection = self.request.GET.get("search")
            if selection:
                queryset = TV.objects.annotate(
                    similarity=TrigramSimilarity('brand', selection)
                    ).filter(similarity__gt=0.3).order_by('-similarity')

        return queryset

    def list(self, request, *args, **kwargs):
        response = super(TVViewSet, self).list(request, args, kwargs)

        tvs = self.get_queryset().values('brands', 'stores__store')
        brandss = set([])
        prices = set([])
        for item in tvs:
            brands.add(item['brand'])
            prices.add(item['store__price'])

        filters = OrderedDict()
        filters['min_price'] = min(prices)
        filters['max_price'] = max(prices)
        filters['brand'] = brands 
        return response

此外,我已经定义了电视滤镜和电视连续剧,不要发布它不再详细。当我向API提出这样的请求时:

http://myapi/tv/?search=brand_name

在json末尾呈现的可能值列表与获得的TV对象的查询集重合。但如果我提出这样的请求:

http://myapi/tv/?search=brand_name&min_price=1000

过滤可能值和电视对象不一致。在应用django后端过滤器或休息过滤器后,有没有办法获取查询集?

我的主要目标是获取要过滤的所有可能值,以便前端可以显示可用的过滤器,然后最终用户可以应用链过滤器。

0 个答案:

没有答案