如何处理django查询集?

时间:2022-10-15 15:25:00

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?

嘿,我想在一个queryset中处理每个对象的一个属性,然后返回JSON格式?怎么处理呢?

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

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

例如,我想在用户名字段后手动添加一个'*',然后返回JSON格式?还是保持queryset类型?

2 个解决方案

#1


1  

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.

在Django shell中使用它。

JSON format? oh someone else can do that!

JSON格式吗?哦,别人也能做到!

#2


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

关于JSON响应:Django文档

#1


1  

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.

在Django shell中使用它。

JSON format? oh someone else can do that!

JSON格式吗?哦,别人也能做到!

#2


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

关于JSON响应:Django文档