Created
December 5, 2016 08:25
-
-
Save AlwxSin/d9e1442eab754fcb1a2b2441a44ba6eb to your computer and use it in GitHub Desktop.
Django Rest Framework Mixins
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 : )