Mitja Nikolaus | e2928eb | 2018-11-02 15:07:20 +0100 | [diff] [blame] | 1 | """Utility functions for the crashreports app.""" |
| 2 | |
| 3 | from django.shortcuts import get_object_or_404 |
| 4 | |
| 5 | |
| 6 | def get_object_by_lookup_fields(view, lookup_fields): |
| 7 | """Retrieve an object using the provided lookup fields. |
| 8 | |
| 9 | Filter objects by the request parameters given in the view. Use only the |
| 10 | parameters that are given in the lookup field keys set. If a single |
| 11 | object instance matches the filters, it is returned. Otherwise a HTTP 404 |
| 12 | exception is raised. |
| 13 | |
| 14 | :param view: The view containing the request parameters. |
| 15 | :param lookup_fields: Set of keys of request parameters to use. |
| 16 | :return: The matched object. |
| 17 | """ |
| 18 | queryset = view.get_queryset() |
| 19 | query_filter = {} |
| 20 | for field in lookup_fields: |
| 21 | if field in view.kwargs: |
| 22 | query_filter[field] = view.kwargs[field] |
| 23 | obj = get_object_or_404(queryset, **query_filter) |
| 24 | view.check_object_permissions(view.request, obj) |
| 25 | return obj |