【问题标题】:tastypie with django-simple-history - display model history as rest API带有 django-simple-history 的美味派 - 将模型历史显示为 REST API
【发布时间】:2014-01-25 14:18:51
【问题描述】:

我想使用tastepie 分享django 模型历史(由django-simple-history 创建)。 问题是,如何为此目的准备ModelResource

模型历史的访问权限是 model.history 经理。因此,我们可以通过model.history.all()获得模型的所有更改

我想获得什么?例如。我有 django 模型 Task 和 API 端点:

  1. http://127.0.0.1/api/v1/task - 显示所有任务列表
  2. http://127.0.0.1/api/v1/task/1 - 显示所选任务的详细信息
  3. http://127.0.0.1/api/v1/task/1/history - 显示任务编号的历史记录。 1

前两个链接呈现ModelResource的默认行为。到现在为止我有什么?

class TaskResource(ModelResource):

    class Meta:
        # it displays all available history entries for all task objects
        queryset = Task.history.all() 
        resource_name = 'task'

    def prepend_urls(self):
        return [
            url(r"^(?P<resource_name>%s)/(?P<pk>\w[\w/-]*)/history$" % (self._meta.resource_name,),
                self.wrap_view('get_history'),
                name="api_history"),
            ]

    def get_history(self, request, **kwargs):
        #...

get_history 应该返回带有历史条目的包。但是这个方法应该是什么样子? 我想,我需要创建包含所需数据的捆绑包,但不知道我应该怎么做。 有人有简单的历史和美味的经验,可以举一些简单的例子吗?

【问题讨论】:

    标签: django model history tastypie


    【解决方案1】:

    看来,解决方案比我想象的要简单。也许有人在功能中使用了这个:

    class TaskHistoryResource(ModelResource):
       class Meta:
         queryset = Task.history.all()
         filtering = { 'id' = ALL }
    
    class TaskResource(ModelResource):
       history = fields.ToManyField(AssetTypeHistoryResource, 'history')
    
       class Meta:
         # it displays all available history entries for all task objects
         queryset = Task.history.all() 
         resource_name = 'task'
    
       def prepend_urls(self):
         return [
            url(r"^(?P<resource_name>%s)/(?P<pk>\w[\w/-]*)/history$" %(self._meta.resource_name,),
                self.wrap_view('get_history'),
                name="api_history"),
            ]
    
        def get_history(self, request, **kwargs):
          try:
             bundle = self.build_bundle(data={'pk': kwargs['pk']}, request=request)
             obj = self.cached_obj_get(bundle=bundle, **self.remove_api_resource_names(kwargs))
          except ObjectDoesNotExist:
             return HttpGone()
          except MultipleObjectsReturned:
             return HttpMultipleChoices("More than one resource is found at this URI.")
    
          history_resource = TaskHistoryResource()
          return history_resource.get_list(request, id=obj.pk)
    

    稍微改变了解决方案: http://django-tastypie.readthedocs.org/en/latest/cookbook.html#nested-resources

    基本上,需要使用历史条目创建额外的资源。 get_history 方法在id 字段上使用适当的过滤器创建并返回它的实例(在django-simple-history id 字段中包含主要对象的id。修订主键名称history_id

    希望,这会对某人有所帮助。

    【讨论】:

      猜你喜欢
      • 2014-08-04
      • 2020-10-10
      • 2011-10-19
      • 2020-09-29
      • 1970-01-01
      • 1970-01-01
      • 2016-05-20
      • 2011-10-18
      • 1970-01-01
      相关资源
      最近更新 更多