删除django tastypie中的对象

时间:2013-08-16 19:24:18

标签: python django tastypie

我有以下型号:

class Poster(models.Model)
     user = models.OneToOneField(User, primary=True)
     userpicture = models.CharField(max_length = 128 =True)

class Posts(models.Model)
     poster = models.ForeignKey(Poster, related_name = 'post_owner')
     url = models.CharField(max_length = 128)
     time = models.DateTimeField(auto_now_add=True)

class Comment(models.Model):
     user = models.ForeignKey(Poster)
     post = models.ForeignKey(Posts)
     time = models.DateTimeField(auto_now_add=True)
     comment = models.CharField(max_length=140)

海报可以发帖子,其他海报可以对该帖子发表评论。有点像博客的工作方式。我想这样做,以便帖子所有者可以选择删除他自己的评论和其他海报的评论。

我该怎么做呢?

我目前正在使用Django Tastypie。这是我目前的资源:

class DeleteComment(ModelResource):
     class Meta:
          queryset = Comment.objects.all()
          allowed_methods = ['delete']
          resource_name = 'comment-delete'
          excludes = ['id', 'comment', 'post', 'time']
          authorization = Authorization()
          authentication = BasicAuthentication()
          include_resource_uri = False
          always_return_data = True

但这有效!这允许任何用户删除任何评论,即使它不是自己哪个不好!怎么样?

只需将 DELETE 请求发送至:myapp.com:8000/v1/posts/comment-delete/8/即可删除评论 id 8 的对象。这是设置失败的地方。

我需要一种方法,以便只有帖子的帖子所有者可以在帖子上删除他的评论和其他人的评论。

2 个答案:

答案 0 :(得分:3)

最好使用Authorization强制执行。

您需要实现delete_detail方法以返回True或False,例如:

def delete_detail(self, object_list, bundle):
    return bundle.obj.user == bundle.request.user

答案 1 :(得分:2)

正如tastyie cookbook中所述。也许你可以这样做:

class DeleteComment(ModelResource):

    def obj_delete(self, bundle, **kwargs):
         # get post id
         comment = Comment.objects.get(pk=bundle.data.id) # or or whatever way you can get the id
         # delete all comments with that post id
         Comment.objects.filter(post=comment.post).delete()
         return super(DeleteComment, self).obj_delete(bundle, user=bundle.request.user)

    def apply_authorization_limits(self, request, object_list):
        return object_list.filter(user=request.user)