Python Tastypie获取或创建对象
可以在tastypie中创建默认对象吗?我想在第一次通过RESTAPI检索对象时创建一个对象,因此总是有一个返回值。我可以在Python Tastypie获取或创建对象,python,django,rest,tastypie,Python,Django,Rest,Tastypie,可以在tastypie中创建默认对象吗?我想在第一次通过RESTAPI检索对象时创建一个对象,因此总是有一个返回值。我可以在脱水中执行此操作,但我还需要考虑获取参数来创建对象。重载的最佳方法是什么?如何重载相关对象(GET参数所指的对象)?我可能已经找到了“a”解决方案 在ModelResource中,我重载了obj\u get\u列表: def obj_get_list(self, bundle, **kwargs): if bundle.request.method == 'GET'
脱水
中执行此操作,但我还需要考虑获取
参数来创建对象。重载的最佳方法是什么?如何重载相关对象(GET参数所指的对象)?我可能已经找到了“a”解决方案
在ModelResource
中,我重载了obj\u get\u列表
:
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
这个解决方案有什么问题吗?有人能预见到意外的副作用吗?另一种方法是覆盖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\u identifier*