Skip to content

Instantly share code, notes, and snippets.

@AlwxSin
Created December 5, 2016 08:25
Show Gist options
  • Save AlwxSin/d9e1442eab754fcb1a2b2441a44ba6eb to your computer and use it in GitHub Desktop.
Save AlwxSin/d9e1442eab754fcb1a2b2441a44ba6eb to your computer and use it in GitHub Desktop.
Django Rest Framework Mixins
class BriefListMixin:
"""
Sometimes front-end needs brief list of models
Need to override brief_fields mapping like
{'frontend_name': 'model_field'}
"""
brief_fields = {}
@decorators.list_route(methods=['GET', ], url_path='brief')
def brief_list(self, request):
"""
Brief list
"""
result = []
queryset = self.filter_queryset(self.get_queryset())
for s in queryset: # type: Model
field = {}
for key, value in self.brief_fields.items():
field[key] = getattr(s, value)
result.append(field)
return Response(result)
class ProtectedForeignKeyDeleteMixin:
"""
If foreign key has Protected on delete mode, DRF can't process this.
"""
def destroy(self, request, *args, **kwargs):
instance = self.get_object()
try:
instance.delete()
return_status = status.HTTP_204_NO_CONTENT
msg = None
except ProtectedError:
return_status = status.HTTP_403_FORBIDDEN
fields_dict = instance._meta.fields_map
msg = dict()
msg['message'] = "One of the following fields prevent deleting this instance: {}"\
.format(", ".join(fields_dict.keys()))
msg['fields'] = fields_dict.keys()
return Response(status=return_status, data=msg)
@solalsabbah
Copy link

solalsabbah commented Feb 18, 2019

Hello, did you write to avoid a 500 server error ?
I am looking for a solution. How to implement this ? I know it's an old post but if you remember will be great : )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment