Django,从模型更新
假设我有这个小模型:
class Deal(models.Model):
purchases = models.IntegerField(default=0)#amount of purchases so far
increase_purchases(self,to_add):
self.update( purchases =self.purchases + to_add)
当我尝试从shell使用这个increase_purchases模型时:
>>> x = Deal.objects.get(id=1)
>>> x.increase_purchases(4)
AttributeError: 'Deal' object has no attribute 'update'
如何为模型编写适当的函数,以便我可以根据需要更新所选的查询购买?
assume I have this little model:
class Deal(models.Model):
purchases = models.IntegerField(default=0)#amount of purchases so far
increase_purchases(self,to_add):
self.update( purchases =self.purchases + to_add)
when I try to use this increase_purchases model from shell:
>>> x = Deal.objects.get(id=1)
>>> x.increase_purchases(4)
AttributeError: 'Deal' object has no attribute 'update'
How can I write a proper function to the model so that I can update the selected querys purchases as I want ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
根据您的示例和描述,您可能想要这样的内容:
我同意伊格纳西奥;修改对象然后保存。所以在 shell 中:
是的,我在 Deal 模型中稍微重命名了一些东西。这样看起来更具描述性。
Based on your example and description, you probably want something like this:
I agree with Ignacio; modify the object and then save it. So in the shell:
Yes, I renamed things a little bit in the Deal model. It just seemed more descriptive this way.
修改适当的字段,然后在实例上调用
save()
。Modify the appropriate fields then call
save()
on the instance.或者使用 += 表达式来获得更简洁的代码:
Or use the += expression for cleaner code:
在 Django 1.6.2 中。遇到这种行为并使用“过滤器”,然后更新按预期工作。例如,Students.objects.select_for_update().filter(id=3).update(score = 10)
仅供参考:除非您正在处理事务,否则使用 save() 单独修改每个字段可能会在多线程中造成数据不一致环境。当线程 A 在模型上调用 save() 时,另一个线程 B 可能已更改模型字段并保存。在这种情况下,threadA 必须读取更新后的模型并进行更改。
In Django 1.6.2. Encountered this behavior and used a "filter" then update works as expected. For example, Students.objects.select_for_update().filter(id=3).update(score = 10)
Just fyi: Unless you are handling transactions, modifying each field separately using save() might create data inconsistency in a multi-threaded environment. By the time threadA calls save() on a model, another threadB could have changed the model fields and saved. In which case threadA has to read the updated model and change.