Django中的F表达式来解决丢失修改问题
2016-03-01 19:28
381 查看
在使用django开发自己的博客的时候,有一个就是统计每一片博文的访问次数。一开始是这样实现的:
后来越想越觉得不对。如果两个用户,在第一个用户访问,代码执行到article.save()之前,第二个用户开始访问了,这样,第一个用户的加一操作会被第二个用户的操作覆盖,这就是所谓的“丢失修改”问题。
后来查阅了很多文档,终于还是在Django的官方文档中发现了F表达式这个东西。这个东西就是用于代表参数中的属性的值。
官方文档如此介绍:
Although
When Django encounters an instance of
field represented by
Whatever value is or was on
意思就是,一旦遇到F表达式,Django就会直接在数据库层面进行操作,而不会先把那个属性的值读到内存。事实上,Django是完全不知道那一个值的大小,因为所有动作都是在数据库上进行的。
所以,我的代码要改写成这样:
这样就不会出现“丢失修改”问题了。
def readArticle(req,article_id): article = Article.objects.get(id=article_id) article.read_time+=1 #read_time就是一片博文的访问次数 article.save() return render(req,"article.html",{'post':article,'post_read_time':post_read_time})#把值传到模板中
后来越想越觉得不对。如果两个用户,在第一个用户访问,代码执行到article.save()之前,第二个用户开始访问了,这样,第一个用户的加一操作会被第二个用户的操作覆盖,这就是所谓的“丢失修改”问题。
后来查阅了很多文档,终于还是在Django的官方文档中发现了F表达式这个东西。这个东西就是用于代表参数中的属性的值。
官方文档如此介绍:
from django.db.models import F reporter = Reporters.objects.get(name='Tintin') reporter.stories_filed = F('stories_filed') + 1 reporter.save()
Although
reporter.stories_filed = F('stories_filed') + 1looks like anormal Python assignment of value to an instance attribute, in fact it’s an SQLconstruct describing an operation on the database.
When Django encounters an instance of
F(), it overrides the standard Pythonoperators to create an encapsulated SQL expression; in this case, one whichinstructs the database to increment the database
field represented by
reporter.stories_filed.
Whatever value is or was on
reporter.stories_filed, Python never gets toknow about it - it is dealt with entirely by the database. All Python does,through Django’s
F()class, is create the SQL syntax to refer to the fieldand describe the operation.
意思就是,一旦遇到F表达式,Django就会直接在数据库层面进行操作,而不会先把那个属性的值读到内存。事实上,Django是完全不知道那一个值的大小,因为所有动作都是在数据库上进行的。
所以,我的代码要改写成这样:
def readArticle(req,article_id): article = Article.objects.get(id=article_id) post_read_time=article.read_time+1 article.read_time=F('read_time')+1 article.save() return render(req,"article.html",{'post':article,'post_read_time':post_read_time})
这样就不会出现“丢失修改”问题了。
相关文章推荐
- 关于Go语言共享内存操作的小实例
- Xcode警告Category is implementing a method which will also be implemented by its primary class 处理
- POJ2195 Going Home(SPFA最小费用最大流)
- go liteIDE
- Django 路由
- django:field字段类型
- mongo2.4_point_in_time_recovery
- USACO 2016 Jan Gold 愤怒的奶牛(Angry Cows)
- 如何在WindowsAzure上搭建Mean stack环境之如何在中国版Azure上搭MangoDB
- google perftools分析程序性能
- django1.9的static文件配置
- 减少集成google-play-service-lib后编译的apk的大小
- Go语言三大框架点评
- 操作系统 之 银行家算法
- Django:locals()小技巧
- Go语言异常处理defer\panic\recover
- Dragonboard 410C 之 开发板设计规范
- HDU4341-Gold miner-分组DP
- Google2015校招在线測试题1----扫雷最少点击次数
- 算法代码实现之三向切分快速排序,Golang(Go语言)实现