2013-08-16 87 views
3

我有以下型號:刪除對象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/ /它會刪除該具有ID的註釋對象。這是設置失敗的地方。

我需要一種方式,只有帖子的帖子所有者可以刪除他的評論和其他人在他帖子上的評論。

回答

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) 
+0

將這個帳戶被他人創建的海報評論的對象的刪除? – noahandthewhale

+0

我試過你的解決方案,發表評論的海報無法刪除他的評論:( – noahandthewhale

+0

刪除帖子,而應該刪除評論以及 –

3

這是最好的執行Authorization

您需要實現delete_detail方法返回真或假,例如:

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

顯而易見,但要明確說明,因爲它顯然不是我最初的, 如果返回True,則將在obj_delete方法中刪除該對象。 如果返回「False」,則該對象不會在obj_delete中被刪除。方法。 obj_delete方法用於實際刪除一個對象,delete_detail決定它是否將被刪除。 –