2013-02-27 2 views
6

Django Rest 프레임 워크를 사용하고 있습니다. API의 웹 브라우저 부분에서 'options'버튼을 클릭하면 다음을 볼 수 있습니다 ...Django Rest 프레임 워크 옵션에서 필터 및 순서 표시 요청

HTTP 200 OK Vary: Accept Content-Type: text/html Allow: HEAD, GET, OPTIONS 
{ 
    "parses": [ 
     "application/json", 
     "application/x-www-form-urlencoded", 
     "multipart/form-data" 
    ], 
    "renders": [ 
     "application/json", 
     "text/html" 
    ], 
    "name": "Products", 
    "description": "API endpoint." 
} 

내 질문에 어쨌든 나는이 모든 필터 옵션을 다른 URL로 지정할 수 있습니까?

답변

6

보기에서 .metadata() 메서드를 재정 의하여 OPTIONS을 원하는대로 되돌릴 수 있습니다.

여기를 참조하십시오 : 2015의 같은 https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/views.py#L340


업데이트 : http://www.django-rest-framework.org/api-guide/metadata/

+0

더 잘 설명 할 수 있습니까?보기에서 .metadata()을 재정의 할 수 있습니까? 이 링크는 'line 340'을 가리키고 있지만 어떤 방법을 참조하는지는 모르겠다. – ePascoal

+1

위 업데이트를 참조하십시오. –

0

당신은 완전히이 작업을 수행 할 수 있습니다 : 우리는 지금이 쉽게 사용자 정의 메타 데이터 API가 있습니다. 여기에 custom metadata class이 있습니다. StackOverflow에서이 기사를 계속 읽었습니다. 여기에는 사용 가능한 모든 필터, 유형 및 선택 사항이 나열됩니다. 또한 클래스에서 사용할 수있는 주문 필드를 나열 어딘가에 프로젝트에서, 다음 DEFAULT_METADATA_CLASS을 설정

class SimpleMetadataWithFilters(SimpleMetadata): 

    def determine_metadata(self, request, view): 
     metadata = super(SimpleMetadataWithFilters, self).determine_metadata(request, view) 
     filters = OrderedDict() 
     if not hasattr(view, 'filter_class'): 
      # This is the API Root, which is not filtered. 
      return metadata 

     for filter_name, filter_type in view.filter_class.base_filters.items(): 
      filter_parts = filter_name.split('__') 
      filter_name = filter_parts[0] 
      attrs = OrderedDict() 

      # Type 
      attrs['type'] = filter_type.__class__.__name__ 

      # Lookup fields 
      if len(filter_parts) > 1: 
       # Has a lookup type (__gt, __lt, etc.) 
       lookup_type = filter_parts[1] 
       if filters.get(filter_name) is not None: 
        # We've done a filter with this name previously, just 
        # append the value. 
        attrs['lookup_types'] = filters[filter_name]['lookup_types'] 
        attrs['lookup_types'].append(lookup_type) 
       else: 
        attrs['lookup_types'] = [lookup_type] 
      else: 
       # Exact match or RelatedFilter 
       if isinstance(filter_type, RelatedFilter): 
        model_name = (filter_type.filterset.Meta.model. 
            _meta.verbose_name_plural.title()) 
        attrs['lookup_types'] = "See available filters for '%s'" % \ 
              model_name 
       else: 
        attrs['lookup_types'] = ['exact'] 

      # Do choices 
      choices = filter_type.extra.get('choices', False) 
      if choices: 
       attrs['choices'] = [ 
        { 
         'value': choice_value, 
         'display_name': force_text(choice_name, strings_only=True) 
        } 
        for choice_value, choice_name in choices 
       ] 

      # Wrap up. 
      filters[filter_name] = attrs 

     metadata['filters'] = filters 

     if hasattr(view, 'ordering_fields'): 
      metadata['ordering'] = view.ordering_fields 
     return metadata 

넣어, 당신은 지금처럼 OPTIONS 요청에 대한 새 키를 가진 모든 세트해야한다 :

"filters": { 
    "sub_opinions": { 
     "type": "RelatedFilter" 
    }, 
    "source": { 
     "type": "MultipleChoiceFilter", 
     "choices": [ 
      { 
       "display_name": "court website", 
       "value": "C" 
      }, 
     ] 
    } 
    ...more... 
} 

이 또한 DRF 다른 곳에서 처리하는 것 방법을 미러링, choices를 표시합니다.

관련 문제