2011-01-12 86 views
2

嘿,我想處理一個查詢集內每個對象的一個​​屬性,之後我想返回JSON格式?如何處理?如何處理Django查詢集?

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

例如,我想手動添加用戶的名稱字段「*」之後,再返回爲JSON格式?或保持查詢集類型?

回答

1

你也可以遍歷一個查詢集,每個元素都是一個單獨的對象,所以是這樣的:在Django的外殼,它

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

發揮。

JSON格式?哦別人可以做到這一點!

+1

`json.dumps(starnames)`會做到這一點。 – 2011-01-12 13:10:38

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 

用法:

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

關於JSON響應:Django Docs