Tastypie get_or_create对象

时间:2013-07-06 06:39:29

标签: python django rest tastypie

是否可以在tastypie中创建默认对象?我想在第一次通过REST api检索时创建一个对象,所以总是返回一个值。我可以在dehydrate中执行此操作,但我还需要考虑GET参数来创建对象。什么是最好的重载方法,以及如何相关对象(GET参数引用)?

2 个答案:

答案 0 :(得分: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

调用它的网址将有一个GET参数/url/to/resource?entity=1

这个解决方案有什么问题吗?任何人都可以预见到不良副作用吗?

答案 1 :(得分:0)

另一种方法是覆盖obj_get函数。

/url/to/resource/identifier/*some_identifier*

这允许使用以下格式的网址:DateTime