1

我有一个接受用户uuidphonenumber用户的端点

url(r'^(?P<uuid>[0-9A-Fa-f+-]+)/$', view_name.as_view()),

现在,我有一个相应过滤的查询集。这里是。

class UserDetails(RetrieveUpdateAPIView):
    serializer_class = UserSerializer
    lookup_field = 'uuid'

    def get_queryset(self):
        """
        Over-riding queryset.

        Filter user based on the user_id(Works for both msisdn & uuid).
        """
        msisdn_or_uuid = self.kwargs[self.lookup_field]
        queryset = Users.objects
        try:  # checking if the forwarded param is user_id or msisdn.
            UUID(msisdn_or_uuid)
            instance = queryset.filter(uuid=msisdn_or_uuid)
        except ValueError:
            instance = queryset.filter(msisdn=msisdn_or_uuid)
            print instance # prints a queryset. But returns 404.
        return instance

现在的问题是,每当传递电话号码时,它都会返回 404 not found。但这些物体显然是存在的。

DRF 中是否有任何设置可以同时过滤两个或多个字段而不会覆盖get_queryset.??

我找到了一个相关的问题,但无法使其工作。我哪里错了?

更新

这是我尝试过的。有用。但想听听更好的解决方案(如果有的话)

class FilterByUuidMsisdnMixin(object):
    """
    Mixin to filter by multiple lookup_fields.

    Apply this mixin to any view or viewset to get multiple field (only uuid &
    msisdn) filtering, instead of the default single field filtering.
    """

    def get_object(self):
        """Over-riding get_object."""
        queryset = self.get_queryset()             # Get the base queryset
        queryset = self.filter_queryset(queryset)  # Apply any filter backends
        field = self.kwargs.get(self.lookup_field)
        filters = {}
        try:  # checking if the forwarded param is user_id or msisdn.
            UUID(field)
            filters['uuid'] = field  # filter by uuid.
        except ValueError:
            filters['msisdn'] = field  # filter by msisdn.

        obj = get_object_or_404(queryset, **filters)  # Lookup the object
        self.check_object_permissions(self.request, obj)  # check permissions.
        return obj
4

0 回答 0