2011-01-12 6 views
2

이봐, 하나의 쿼리 세트 안에 모든 객체의 속성 하나를 처리하고 싶습니다. 그런 다음 JSON 포맷을 반환하겠습니까? 어떻게해야할까요?장고 쿼리 세트를 처리하는 방법은 무엇입니까?

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

예를 들어, 내가 수동으로 '*'후 사용자 이름 필드를 추가하고 JSON 형식으로 반환하려면? 또는 queryset 유형을 유지?

답변

1

할 수 있습니다 쿼리 세트 이상 반복하고, 각 요소는 단일 객체, 그래서 뭔가 같은 : 장고 쉘에서 그것으로

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

플레이.

JSON 형식? 오 다른 사람이 그렇게 할 수 있습니다!

+1

'json.dumps (starnames)'을 할 것입니다. –

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 

사용법 :

JSON 응답에 대해
class YourView(ProcessQuerySet, AnyDjangoGenericView): 
def get_queryset(self): 
    queryset = SomeModel.objects.all() 
    return self.process_queryset(queryset) 

: Django Docs

관련 문제