티스토리 뷰

아래의 예제는 모델별로 원하는 정보를 id 와 text 라는 키로 프로세싱 하여 되돌려주는 API 이다.


annotate() 로 리턴필드명을 지정하고,

Concat() 를 사용하여 model 의 필드 값들을 붙일 수 있으며, output_field 값을 지정하여 필드 타입도 지정할 수 있다.

필드값 사이사이에 일반 문자열을 넣고 싶다면 Value 라는 Object 를 활용할 수 있다.


class MyAPIView(APIView): def get(self, req): ret = APIResult() ret_dic = dict() if ('key' not in req.GET): ret_dic['error'] = "키 정보가 없습니다." else: if ('search' in req.GET) and (req.GET['search']): need_search = True items = [] if req.GET['key'] == 'model1': text = functions.Concat(V('[ #'), 'id', V(' ] '), 'title', output_field=CharField()) items = MyModel1.objects.annotate(id=F('uid'), text=text).values('id', 'text') elif req.GET['key'] == 'model2': text = functions.Concat(V('[ #'), 'id', V(' - '), 'state', V('] '), 'title', output_field=CharField()) items = MyModel2.objects.annotate(id=F('field1'), text=text).values('id', 'text') if need_search: items = items.filter(text__contains=req.GET['search']) ret.add_object('items', list(items.order_by('-id'))) return JsonResponse(data)


댓글