2011-06-07 69 views
3

我正在使用django-piston來編寫RESTful Web服務並出現問題。如何更新模型但在Django中返回未修改的模型?

在models.py:

class Status(models.Model): 
    user = models.ForeignKey(User) 
    content = models.TextField(max_length=140) 

class StatusReply(models.Model): 
    user = models.ForeignKey(User) 
    reply_to = models.ForeignKey(Status, related_name='replies') 
    content = models.TextField(max_length=140) 
    has_read = models.BooleanField(default=False, help_text="has the publisher of the status read the reply") 

在handlers.py:

class StatusHandler(BaseHandler): 
    allowed_methods = ('GET', 'POST', 'DELETE') 
    model = Status 
    fields = ('id', 
       ('user', ('id', 'username', 'name')), 
       'content', 
       ('replies', ('id', 
          ('user', ('id', 'username', 'name')), 
          'content', 
          'has_read'), 
      ), 
      ) 

    @need_login 
    def read(self, request, id, current_user): # the current_user arg is an instance of user created in @need_login 
     try: 
      status = Status.objects.get(pk=id) 
     except ObjectDoesNotExist: 
      return rc.NOT_FOUND 
     else: 
      if status.user == current_user: #if current_user is the publisher of the status, set all replies read 
       status.replies.all().update(has_read=True) 
      return status 

在處理程序,它通過ID返回一個特定的狀態。現在我想返回status.replies.all().update(has_read=True)之前的狀態,但也要在數據庫中進行更新操作。怎麼做?提前致謝。

回答

2

不知道我是否明白你需要什麼。據我瞭解您的代碼,status.replies.all().update(has_read=True)不會更改status但只更改答覆。如果這是真的,代碼應該做你想做的。如果不是,你可以做的status副本並返回副本:

 if status.user == current_user: 
      old_status = status.make_copy() 
      status.replies.all().update(has_read=True) 
      return old_status 
     return status 

或者你只是想方法來提前返還和異步做數據庫更新?那麼你應該看看celery,也許this nice explanation