Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Tastypie获取或创建对象_Python_Django_Rest_Tastypie - Fatal编程技术网

Python Tastypie获取或创建对象

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'

可以在tastypie中创建默认对象吗?我想在第一次通过RESTAPI检索对象时创建一个对象,因此总是有一个返回值。我可以在
脱水
中执行此操作,但我还需要考虑
获取
参数来创建对象。重载的最佳方法是什么?如何重载相关对象(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*