[Django]-How to process a django queryset?

2👍

You can loop over a query set, and each element is a single object, so something like:

starnames = [ n.username+"*" for n in results]

play with it at the Django shell.

JSON format? oh someone else can do that!

1👍

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

Usage:

class YourView(ProcessQuerySet, AnyDjangoGenericView):
def get_queryset(self):
    queryset = SomeModel.objects.all()
    return self.process_queryset(queryset)

About JSON Response: Django Docs

👤Sultan

Leave a comment