class ProcessQuerySet(object):
"""
A control that allow to add extra attributes for each object inside queryset.
"""
def process_queryset(self, queryset):
""" queryset is a QuerySet or iterable object. """
return map(self.extra, queryset) # Using map instead list you can save memory.
def extra(self, obj):
""" Hook method to add extra attributes to each object inside queryset. """
current_user = self.request.user # You can use `self` to access current view object
obj.username += '*'
return obj
Использование:
class YourView(ProcessQuerySet, AnyDjangoGenericView):
def get_queryset(self):
queryset = SomeModel.objects.all()
return self.process_queryset(queryset)
Об ответе JSON: Django Docs