【发布时间】:2017-04-03 10:58:46
【问题描述】:
我有一个 Tastypie API,我想在 POST 请求中获取所创建资源的“id”,所以我找到的唯一解决方案是返回整个对象的“always_return_data”。
from tastypie.resources import ModelResource
from tastypie.authorization import Authorization
from tastypie.authentication import SessionAuthentication
from myproject.core.models import MyModel
class MyResource(ModelResource):
...
class Meta:
queryset = MyModel.objects.all()
resource_name = 'mymodel'
allowed_methods = ['get', 'put', 'post']
authentication = SessionAuthentication()
authorization = Authorization()
always_return_data = True # Added later
这很好用。但是一开始我已经编写了测试并且有:
对于 POST:self.assertHttpCreated(self.api_client.post('self.detail_url', format='json', data=data))
对于 PUT:self.assertHttpAccepted(self.api_client.put(self.detail_url, format='json', data=new_data))
现在,在我设置 always_return_data = True 旧测试失败后,因为 POST 返回 200 而不是 201,PUT 重新调整 200 而不是 [202/204]
除了用assertHttpOK 替换assertHttpCreated 和assertHttpAccepted 之外,还有其他解决方案吗?或者如果可能的话,是否可以在不设置always_return_data = True 的情况下仅在POST 请求中返回新创建资源的“id”。欢迎任何建议。谢谢。
【问题讨论】: