2013-10-07 2 views
0

tastypie에서 하나의 필드 만 반환하는 방법?

class PostResource(ModelResource): 

    children = fields.ToManyField('MyApp.api.resources.PostResource', 
       attribute='comments', full=True, null=True) 

는 기본적으로, 나는 단지이 아이 필드를 반환하고 평평하게 할 .. 내가 자원 아래와 같이 있다고 가정하자.


[ {child-1-data}, {child-2-data} ]
보다는 모양을 { children: [ {child-1-data}, {child2-data} ] }

내가 어떻게 할 수 있습니까?

또한 동일한 모델 클래스의 다른 표현을 원한다면 새로운 리소스 클래스를 작성해야합니까?

class PostNormalResource(ModelResource): 
     class Meta: 
      queryset= models.Post.objects.all() 
      fields = ['text', 'author'] 

답변

0

찾고있는 대답은 아니지만 내가 발견 한 일부 발견 사항입니다.

일반적으로 dehydrate 번들 데이터를 수정합니다. tastypie cookbook을 참조하십시오. tastypie 시리얼 라이저는이 사전을하지 직렬화 찾고으로,

def dehydrate(self, bundle): 
    # Replace all data with a list of children 
    bundle.data = bundle.data['children'] 
    return bundle 

그러나이 오류가 발생하지, AttributeError: 'list' object has no attribute 'items' :

def dehydrate(self, bundle): 
    bundle.data['custom field'] = "This is some additional text on the resource" 
    return bundle 

이 당신의 라인을 따라 당신의 PostResource의 번들 데이터를 조작 할 수있는 제안 명부.

# "site-packages/tastypie/serializers.py", line 239 
return dict((key, self.to_simple(val, options)) for (key, val) in data.data.items()) 

# .items() being for dicts 

이렇게하면 다른 serializer를 살펴볼 필요가 있습니다. 같은 모델의 다른 표현을 원하는 경우


그리고 둘째 네, 다음을 사용하여 올바른 방향으로 당신을 얻을하는 데 도움이 귀하의 JSON :-)

희망을 처리 할 때 (또는 post['children'] 참조 second ModelResource. 분명히 중복을 피하기 위해 서브 클래스를 만들 수 있습니다.

0

alter_detail_data_to_serialize 메서드를 재정의 할 수 있습니다. 전체 객체가 탈수 된 직후에 호출되므로 결과 사전이 serialize되기 전에 수정 작업을 수행 할 수 있습니다.

class PostResource(ModelResource): 
    children = fields.ToManyField('MyApp.api.resources.PostResource', 
      attribute='comments', full=True, null=True) 

    def alter_detail_data_to_serialize(self, request, data): 
     return data.get('children', []) 

동일한 모델의 다른 표현은 - 네. 기본적으로 모호성으로 이어지고 유지하기가 어려우므로 단일 표현을 많은 표현으로 만들면 안됩니다.

관련 문제