我的端点接受用户的uuid
或phonenumber
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未找到。但这些对象显然存在。
DRF中是否有任何设置同时过滤两个或多个字段而不会覆盖get_queryset
。
我找到了related question,但无法使其正常运行。我哪里错了?
更新
这是我尝试过的。有用。但是想听听更好的解决方案(如果有的话)
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