【问题标题】:Deleting a queryset using tastypie使用 sweetpie 删除查询集
【发布时间】:2014-03-18 09:12:20
【问题描述】:

Tastypie 允许删除资源列表中的对象。

http://django-tastypie.readthedocs.org/en/v0.9.9/interacting.html#deleting-a-whole-collection-of-resources

我想删除资源的子集。假设我有一个/api/foo/ 的 api 端点,我想使用 pk 列表对/api/foo/ 执行删除操作,并且只删除那些对象,而不是集合中的所有对象。

有没有办法用美味派做到这一点?

【问题讨论】:

    标签: python django rest tastypie


    【解决方案1】:

    您可以使用负责执行删除的prepend_urls 添加url。

    就像在您的班级中一样,将添加以下两种方法。

    根据需要修改代码。这里我先进行了身份验证。

    def prepend_urls(self):
        params = (self._meta.resource_name, trailing_slash())
        return [
            url(r"^(?P<resource_name>%s)/delete%s$" % params, self.wrap_view('foo_delete'), name="api_foo_delete")
        ]
    
        ## (?P<resource_name>%s)  will be /api/foo  if your resource name is foo
    
    def foo_delete(self, request, **kwargs):
        """ 
        Get pks to delete from post . 
        pks = request.POST.getlist('pks[]') 
        you can use split if you are sending pks by comma separated .
        pks = (request.POST.get('pks')).split(',')
        """
        self.method_check(request, allowed=['post'])
        self.is_authenticated(request)
        if request.user and request.user.is_authenticated():
            ### perform delete operation of pk . 
            return self.create_response(request, { 'success': True })
        else:
            return self.create_response(request, { 'success': False, 'error_message': 'You are not authenticated, %s' % request.user.is_authenticated() })
    

    【讨论】:

    • 如何在foo_delete 中获取捆绑包?我想打电话给self.obj_get_list,但这需要捆绑包,这在self 上不可用。
    • @shabda 您可以使用 from tastypie.bundle import Bundle 然后 bundle = Bundle(request=request, obj=&lt;resource_obj&gt;) 创建捆绑包。这里resource_obj 是您将使用&lt;model_class&gt;.objects.get() 获得的对象。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-27
    • 2011-06-01
    • 1970-01-01
    • 2014-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多