【问题标题】:How to update a model but return unmodified model in Django?如何在 Django 中更新模型但返回未修改的模型?
【发布时间】:2011-09-09 23:48:44
【问题描述】:

我正在使用django-piston 编写一个 RESTful Web 服务,但遇到了问题。

在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) 之前的状态,但还要在数据库中进行更新操作。怎么做?提前致谢。

【问题讨论】:

    标签: python django django-models django-piston


    【解决方案1】:

    不确定我是否了解您的需求。据我了解您的代码,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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-11
      • 1970-01-01
      相关资源
      最近更新 更多