英文:
Filter Backends Django Rest Framework List API View
问题
抱歉,我只回答不包含代码的请求。以下是您要翻译的内容:
Excuse me devs, I want to ask about Django generics List API View filter_backends, how can i return none / data not found when the param is wrong or empty?
# My Django Views
class FilterTablePVPlantByPVOwnerId(filters.FilterSet):
id = filters.CharFilter(
field_name='id', lookup_expr='exact')
class Meta:
model = TablePVPlant
fields = ['id']
class PlantListByClientView(generics.ListAPIView):
queryset = TablePVPlant.objects.all()
serializer_class = PlantListSerializer
filter_backends = [DjangoFilterBackend]
filterset_class = FilterTablePVPlantByPVOwnerId
def list(self, request, *args, **kwargs):
if self.request.query_params:
response = super().list(request, *args, **kwargs)
response.data = {'status': 'success',
'data': response.data, 'msg': 'done'}
return response
英文:
Excuse me devs, I want to ask about Django generics List API View filter_backends, how can i return none / data not found when the param is wrong or empty?
# My Django Views
class FilterTablePVPlantByPVOwnerId(filters.FilterSet):
id = filters.CharFilter(
field_name='id', lookup_expr='exact')
class Meta:
model = TablePVPlant
fields = ['id']
class PlantListByClientView(generics.ListAPIView):
queryset = TablePVPlant.objects.all()
serializer_class = PlantListSerializer
filter_backends = [DjangoFilterBackend]
filterset_class = FilterTablePVPlantByPVOwnerId
def list(self, request, *args, **kwargs):
if self.request.query_params:
response = super().list(request, *args, **kwargs)
response.data = {'status': 'success',
'data': response.data, 'msg': 'done'}
return response
答案1
得分: 1
在Django和Django Rest Framework中,这些类型的问题通过引发异常来处理:
from rest_framework.exceptions import APIException
class BadParameter(APIException):
status_code = 400
default_detail = '参数x错误或为空'
default_code = 'bad_param'
# ...
class PlantListByClientView(generics.ListAPIView):
# ...
def list(self, request, *args, **kwargs):
# ...
if bad_param:
raise BadParameter()
框架的某些部分会为您引发异常,例如,在验证失败时,会引发ValidationError
。
英文:
In both Django and in Django Rest Framework these type of things are dealt with by raising Exceptions:
from rest_framework.exceptions import APIException
class BadParameter(APIException):
status_code = 400
default_detail = 'The parameter x is wrong or empty'
default_code = 'bad_param'
# ...
class PlantListByClientView(generics.ListAPIView):
# ...
def list(self, request, *args, **kwargs):
# ...
if bad_param:
raise BadParameter()
Some parts of the framework will raise exceptions for you, like, for example, serializes rising ValidationError
when validation fails.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论