嗨,我想处理一个查询集中每个对象的一个属性,然后将其以JSON格式返回。如何实现?
results = Sample.objects.filter(user=user)
例如,我想在用户姓名字段后手动添加一个 '*',然后以JSON格式返回?还是保留查询集类型?
嗨,我想处理一个查询集中每个对象的一个属性,然后将其以JSON格式返回。如何实现?
results = Sample.objects.filter(user=user)
starnames = [ n.username+"*" for n in results]
我可以在Django shell中与其一起使用。
JSON格式?哦,其他人可以做那个!
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.dumps(starnames)
就可以了。 - S.Lott