使用Django Rest Framework的辅助获取端点

时间:2018-05-16 08:48:37

标签: django django-rest-framework

我有以下视图集:

class ProductViewSet(
        mixins.RetrieveModelMixin,
        viewsets.GenericViewSet):
    ...

这为我提供了按ID获取产品的端点:

/products/{id}

我尝试添加另一个端点以获取具有辅助唯一密钥(uuid)的产品,以便我将拥有以下端点:

# Existing endpoint, lookup by ID. This I have, and want to keep.
/products/{product_id}  

# Additional endpoint, lookup by UUID. This is what I'm trying to add.
/products/uuid/{product_uuid}

因此API使用者必须能够通过ID或UUID查找产品。

如何使用DRF实现这一目标?我使用的是DRF 3.8.2和Django 1.11。

是否有可能让@action()装饰者提供这个?它的基本行为无法解决问题,因为它只提供模式/products/{id}/detail/products/detail的网址。

1 个答案:

答案 0 :(得分:2)

对于多重查找,您可以编写mixin:

class MultipleFieldLookupMixin(object):
    """
    Apply this mixin to any view or viewset to get multiple field filtering
    based on a `lookup_fields` attribute, instead of the default single field filtering.
    """
    def get_object(self):
        queryset = self.get_queryset()             # Get the base queryset
        queryset = self.filter_queryset(queryset)  # Apply any filter backends
        filter = {}
        for field in self.lookup_fields:
            if self.kwargs[field]: # Ignore empty fields.
                filter[field] = self.kwargs[field]
        obj = get_object_or_404(queryset, **filter)  # Lookup the object
        self.check_object_permissions(self.request, obj)
        return obj

并像这样使用它:

class ProductViewSet(MultipleFieldLookupMixin, 
            mixins.RetrieveModelMixin,
            viewsets.GenericViewSet):
        lookup_fields =( 'product_uuid', 'pk') 

docs

中的更多详细信息