开发者

How to update a model but return unmodified model in Django?

I'm using django-piston to write a RESTful Web Service and have a problem.

in 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")

in 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)
    开发者_如何学Go    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

In the handler, it returned a specific status by id. Now I want to return the status before status.replies.all().update(has_read=True) but also do the update operation in database. How to do it? Thanks in advance.


Not sure if I understand what you need. As I understand your code, status.replies.all().update(has_read=True) doesn't change status but only changes the replies. If that's true, the code should do what you want. If it isn't, you could make a copy of status and return the copy:

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

Or do you just want the method to return early and do the database update asynchronously? Then you should have a look at celery and maybe this nice explanation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜