使用django-rest-framework在一个API端点下过滤多个模型的结果

时间:2017-10-26 01:28:36

标签: python django rest django-rest-framework

我正在使用DRF为我的django应用生成API。 我正在使用ViewSet类,并在自己的路径上为大多数模型公开API端点 我希望允许在Endpoint路径中查看我的TLSCertificate/assets/模型。由于他们都是Organisation实体的子项,因此我希望允许过滤结果Organisation

到目前为止,我有:

serializers.py

class AssetSerializer(serializers.Serializer):
    endpoints = EndpointSerializer(many=True)
    certificates = TLSCertificateSerializer(many=True)

views.py

class AssetFilterSet(filters.FilterSet):
    organisation = filters.ModelChoiceFilter(
        name='organisation', queryset=Organisation.objects.all())

    project = filters.ModelChoiceFilter(
        name='project', queryset=Project.objects.all())

    class Meta:
        model = Endpoint
        fields = ['organisation', 'project']

# the object type to be passed into the AssetSerializer
Asset = namedtuple('Asset', ('endpoints', 'certificates'))

class AssetViewSet(CacheResponseAndETAGMixin, viewsets.ViewSet):
    """
    A simple ViewSet for listing the Endpoints and Certificates in the Asset list.
    Adapted from https://stackoverflow.com/questions/44978045/serialize-multiple-models-and-send-all-in-one-json-response-django-rest-framewor
    """
    # TODO filtering not functional yet
    filter_class = AssetFilterSet
    filter_fields = ('organisation', 'project',)

    queryset = Endpoint.objects.all()

    def list(self, request):
        assets = Asset(
            endpoints=Endpoint.objects.all(),
            certificates=TLSCertificate.objects.all(), )
        serializer = AssetSerializer(assets, context={'request': request})
        return Response(serializer.data)

这适用于返回对象,但不允许进行过滤 如果在这种情况下如何启用过滤,我将不胜感激?

0 个答案:

没有答案