Python 递增数据库中的整型字段计数器
作为Django的初学者,我尝试制作一个简单的应用程序,该应用程序将给出内容被浏览多少次的Http响应。 我创建了一个新的Python 递增数据库中的整型字段计数器,python,django,django-models,models,Python,Django,Django Models,Models,作为Django的初学者,我尝试制作一个简单的应用程序,该应用程序将给出内容被浏览多少次的Http响应。 我创建了一个新的计数器模型,并在其中添加了IntegerField模型计数 class Counter(models.Model): count = models.IntegerField(default=0) def __int__(self): return count 在视图中,我从counter()类中创建了一个变量counter,并尝试将+1添加到
计数器
模型,并在其中添加了IntegerField模型计数
class Counter(models.Model):
count = models.IntegerField(default=0)
def __int__(self):
return count
在视图中,我从counter()
类中创建了一个变量counter
,并尝试将+1添加到counter.count
integer,但当我尝试保存时,它会给我一个无法保存integer的错误
所以我试着拯救课堂:
def IndexView(response):
counter = Counter()
counter.count = counter.count + 1
counter.save()
return HttpResponse(counter.count)
此方法将继续显示1
,重新加载后无法更改
如何正确更改
IntegerField
模型,使其在每次查看后都能更新,即使服务器重新加载也能保存?问题
是的,但是您正在为每个请求创建一个新的计数器对象,它从0开始,这就是您的问题
def IndexView(response):
counter = Counter() # This creates a new counter each time
counter.count = counter.count + 1
counter.save()
return HttpResponse(counter.count)
您在上面所做的操作将导致数据库中出现一组计数器对象,其count=1
解决方案
下面的示例演示如何使用get\u或\u create()
首先,我们需要将计数器与例如页面(或任何东西)相关联,但我们需要某种方法来识别它并从数据库中获取它
然后:
避免在count=count+1时可能发生的竞争条件
为了避免比赛条件,请使用
每次执行Counter()
,都会在数据库中创建一个新对象,其中字段count
的值将为0,并将其递增1。您需要再次获取相同的对象。非常感谢,有没有其他方法可以更改IntegerField?这不是问题,您已经在更改IntegerField
,只是在每次以count=0
默认值开头的新对象(数据库行)上。您所做的是在数据库中生成一组计数器对象,其count=1
。我的示例演示了如何使用get\u或\u create()
class Counter(models.Model):
count = models.IntegerField(default=0)
page = models.IntegerField() # or any other way to identify
# what this counter belongs to
def IndexView(response):
# Get an existing page counter, or create one if not found (first page hit)
# Example below is for page 1
counter, created = Counter.objects.get_or_create(page=1)
counter.count = counter.count + 1
counter.save()
return HttpResponse(counter.count)
# When you have many requests coming in,
# this may have outdated value of counter.count:
# counter.count = counter.count + 1
# Using an F expression makes the +1 happen on the database
from django.db.models import F
counter.count = F('count') + 1