【问题标题】:REST urls with tastypie带有美味派的 REST url
【发布时间】:2011-10-19 05:32:34
【问题描述】:

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

【问题讨论】:

    标签: django rest tastypie


    【解决方案1】:

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

    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,它指向一个视图(我将其命名为 dispatch_list_with_date),它可以执行您想要的操作。

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

    您的视图可能与此非常相似

    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
    

    您可以通过向 Meta 类添加过滤属性来获得此功能

    但这是个人喜好。

    【讨论】:

    • 啊,好吧,所以我认为如果我想实现前者,最好不要使用 sweetpie。因为无论如何我都可以使用 vanilla django 的 url_conf 来实现它。
    • 我非常喜欢 Tastypie 的额外功能和格式,但可以肯定的是,给猫剥皮的方法总是不止一种。
    • 感谢您提供的好例子!非常有用。
    • tastepie 代码中的注释:不推荐使用 override_urls。将被 v1.0.0 删除。请改用prepend_urls
    • 是的,很快您将不得不使用 prepend_urls。更新了回复。
    猜你喜欢
    • 2014-01-25
    • 2012-10-30
    • 2014-01-23
    • 1970-01-01
    • 2012-04-18
    • 2021-12-19
    • 2015-03-21
    • 1970-01-01
    • 2012-01-29
    相关资源
    最近更新 更多