2015-04-04 39 views
0

我正在将现有的API从Django Piston迁移到Django Tastypie。我正在使用Django 1.7。Django Tastypie:通过defaut输出JSON,但也支持其他格式?

默认情况下,现有API输出JSON,但如果将?format=xml附加到URL,则支持XML查询。

我很难找出如何在Tastypie中进行复制。有a very similar question here,但所有的答案只解释如何完全禁用除JSON以外的所有其他格式。所以我想知道是否可以在Tastypie中做到这一点。

如果我这样做,在我的设置文件:

TASTYPIE_DEFAULT_FORMATS = ['json'] 

JSON成为默认的,但我不能那么输出XML与?format=xml参数,因为XML被禁用。

同样,如果我将determine_format方法添加到资源。

是否可以指定JSON作为默认格式,但也允许XML?

+0

您是否在ModelResources的meta类中设置了“序列化程序”属性?请参阅:http://django-tastypie.readthedocs.org/en/latest/serialization.html – kchan 2015-04-04 16:35:15

回答

0

您可以将默认格式的determine_format覆盖为JSON。它也可以用于其他格式。

class MyAppResource(ModelResource): 
    """It is inheriting Model Resources of tastypie""" 

    def determine_format(self, request): 
     """ 
     return application/json as the default format 
     """ 
     fmt = determine_format(request, self._meta.serializer,\ 
           default_format=self._meta.default_format) 
     if fmt == 'text/html' and 'format' not in request: 
      fmt = 'application/json' 
     return fmt 

现在,而不是Base作为ModelResource使用MyAppResource为您的资源类。