Tastypie API仅返回给定参数的一个对象

时间:2014-02-21 14:48:56

标签: json django resources tastypie

我正在覆盖get_obj_list函数。遵循一些参数和随机函数我想返回一个与参数后面的实际对象相关的对象。这很好用。我怎样才能只返回这个obj而不是一个条目列表?还有其他功能更符合我的目的吗?

class SentenceRandomResource(ModelResource):

    class Meta:
        queryset = Sentence.objects.filter()
        resource_name = 'sentence/random'
        always_return_data = True
        authorization = ReadOnlyAuthorization()
        filtering = {'internal': ALL}

    def obj_get_list(self, bundle, **kwargs):

        if 'case' in bundle.request.GET.keys() and 'lemma' in bundle.request.GET.keys() :
            if 'number'  in bundle.request.GET.keys() :
                words = Word.objects.filter(case = bundle.request.GET['case'], number = bundle.request.GET['number'], lemma = bundle.request.GET['lemma'])
            else :
                words = Word.objects.filter(case = bundle.request.GET['case'], lemma = bundle.request.GET['lemma'])
            number_of_words = len(words)
            if number_of_words > 0 :
                random_index = int(random.random()*number_of_words)+0
                random_word = words[random_index]
                sentence = random_word.sentence

                return [sentence]
            else: ...

        else: ...

1 个答案:

答案 0 :(得分:2)

感谢方法prepend_url,您可以添加一些RESTful原则中未包含的特殊功能。

import random
from tastypie.http import HttpBadRequest

class SentenceRandomResource(ModelResource):

    class Meta:
        queryset = Sentence.objects.filter()
        resource_name = 'sentence/random'
        always_return_data = True
        authorization = ReadOnlyAuthorization()
        filtering = {'internal': ALL}

    def prepend_urls(self, *args, **kwargs):
        name = 'get_one_random'
        return [url(r"^(?P<resource_name>%s)/%s%s$" %
                    (self._meta.resource_name, name, trailing_slash()),
                    self.wrap_view(name), name="api_%s" % name)]

    def get_one_random(self, request, **kwargs):
        """
        Gets one random sentence of sentences with provided `case` and `lemma` 
        params.
        """
        case = request.GET.get('case')
        lemma = request.GET.get('lemma')
        number = request.GET.get('number')

        if case and lemma:
            query_params = {'case': case, 'lemma': lemma}
            if number is not None:
                query_params['number'] = number
            words = Word.objects.filter(**query_params)

            word = random.choice(words)
            return self.create_response(request, {'sentence': word.sentence.__dict__})

        else:
            return self.error_response(request, {'error': 'lemma and case are required.'},
                                       response_class=HttpBadRequest)

使用示例:

GET ..../sentence/random/get_one_random/?case=1&lemma=2

{'sentence': 'asdfasdf'}