Is it possible to create a default object in tastypie? I'd like to create an object the first time it's retrieved through the REST api, so there's always a returned value. I could do this in dehydrate
, but I also need to take into account GET
parameters to create the object. What would be the best method to overload and how can I related objects (which the GET parameter refers to)?
问问题
505 次
2 回答
0
我可能找到了“一个”解决方案。
在ModelResource
中,我超载obj_get_list
:
def obj_get_list(self, bundle, **kwargs):
if bundle.request.method == 'GET':
related_id = bundle.request.GET['entity']
# create new object if it doesn't exist and populate with `related_id`
# ...
objects = ModelResource.obj_get_list(self, bundle, **kwargs)
return objects
调用它的 url 将有一个 GET 参数/url/to/resource?entity=1
。
这个解决方案有什么问题吗?谁能预见不良副作用?
于 2013-07-06T08:29:13.683 回答
0
另一种方法是覆盖 obj_get 函数。
def obj_get(self, bundle, **kwargs):
pk = kwargs['pk']
if pk.startswith('identifier'):
pk = pk.replace("identifier/", "")
instance, created = Model.objects.get_or_create(identifier=pk)
kwargs['pk'] = str(instance.pk)
return super().obj_get(bundle, **kwargs)
这允许具有以下格式的 URL:/url/to/resource/identifier/*some_identifier*
于 2018-06-12T09:10:13.037 回答