开发者

How to process a django queryset?

开发者 https://www.devze.com 2023-02-04 19:57 出处:网络
Hey, I want to process one attribute of every object inside one queryset, and after that I want to return the JSON format? How to do with that?

Hey, I want to process one attribute of every object inside one queryset, and after that I want to return the JSON format? How to do with that?

results = Sample.objects.filter(user=user)

For example, I want to manually add an '*开发者_JS百科' after user's name field, and then return as JSON format? or remain the queryset type?


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!


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

0

精彩评论

暂无评论...
验证码 换一张
取 消