我的模型已经“创建”了它们的时间戳。它们会在一天后过期,应该重新创建。
如何让代码在客户端尝试GET
来自TastyPie API的资源时,检查资源是否过期并执行业务逻辑。我知道可以使用过滤器来过滤掉过期的资源,但是我可以删除过期的资源并创建新资源,然后在结果中返回它们吗?
答案 0 :(得分:0)
是的,你可以。例如,您可以覆盖资源的obj_get()
方法。
它的源代码位于:https://github.com/toastdriven/django-tastypie/blob/master/tastypie/resources.py#L1895,看起来像这样:
def obj_get(self, request=None, **kwargs):
"""
A ORM-specific implementation of ``obj_get``.
Takes optional ``kwargs``, which are used to narrow the query to find
the instance.
"""
try:
base_object_list = self.get_object_list(request).filter(**kwargs)
object_list = self.apply_authorization_limits(request, base_object_list)
stringified_kwargs = ', '.join(
["%s=%s" % (k, v) for k, v in kwargs.items()]
)
if len(object_list) <= 0:
raise self._meta.object_class.DoesNotExist(
"Couldn't find an instance of '%s' which matched '%s'." %
(self._meta.object_class.__name__, stringified_kwargs)
)
elif len(object_list) > 1:
raise MultipleObjectsReturned(
"More than '%s' matched '%s'." % (
self._meta.object_class.__name__,
stringified_kwargs
)
)
return object_list[0]
except ValueError:
raise NotFound(
"Invalid resource lookup data provided (mismatched type)."
)
您可以检查在该代码中获得的object_list
,然后应用适当的操作。
或者,您可以在途中使用GET
覆盖get_detail()
method,该{{3}}专门处理对单个资源的obj_get()
个请求。
答案 1 :(得分:0)
更好的方法是覆盖get_object_list
方法。这在此处记录:http://django-tastypie.readthedocs.org/en/latest/cookbook.html#per-request-alterations-to-the-queryset