django - 使用 tastypie 的 REST url

标签 django rest tastypie

我在 django 应用程序中使用 tastypie,并尝试让它映射像“/api/booking/2011/01/01”这样的 URL,该 URL 映射到 URL 中具有指定时间戳的 Booking 模型。该文档没有说明如何实现这一点。

最佳答案

您想要在资源中做的是提供一个

def prepend_urls(self):
    return [
        url(r"^(?P<resource_name>%s)/(?P<year>[\d]{4})/(?P<month>{1,2})/(?<day>[\d]{1,2})%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('dispatch_list_with_date'), name="api_dispatch_list_with_date"),
    ]

方法,它返回一个 url,它指向一个 View (我将其命名为dispatch_list_with_date),它可以执行您想要的操作。

例如,在 base_urls 类中,它指向一个名为“dispatch_list”的 View ,该 View 是列出资源的主要入口点,您可能只想使用自己的过滤来复制该 View 。

您的 View 可能看起来与此非常相似

def dispatch_list_with_date(self, request, resource_name, year, month, day):
    # dispatch_list accepts kwargs (model_date_field should be replaced) which 
    # then get passed as filters, eventually, to obj_get_list, it's all in this file
    # https://github.com/toastdriven/django-tastypie/blob/master/tastypie/resources.py
    return dispatch_list(self, request, resource_name, model_date_field="%s-%s-%s" % year, month, day)

真的,我可能会添加一个 filter到普通列表资源

GET /api/booking/?model_date_field=2011-01-01

您可以通过向元类添加过滤属性来实现此目的

但这是个人喜好。

关于django - 使用 tastypie 的 REST url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6929009/

相关文章:

django - 'RelatedManager' 对象没有属性 'pk'

python - django模型中的自定义保存方法和登录问题

python - 如何在用户资源中插入 user_permissions 字段?

python - 有没有办法否定返回到变量的 bool 值?

api - 请求的资源在 Salesforce 中不存在 [错误]。 Salesforce 有什么问题?

rest - Angularjs ngResource 需要将文件作为字段之一

java - 使用 REST API 遍历 JAVA 中的 Neo4j 节点和关系

python - 向 tastypie 发送经过身份验证的 POST 请求

python - Django Rest Framework使用url加载指定模型

python - GetStream (Django) - 无法丰富通知提要