Django Model Not Updating
I'm trying to count the amount of times a user visits a page: models.py: class Request(models.Model): user = models.ForeignKey(User) view = models.CharField(max_length = 25
Solution 1:
You could do something like this:
models.py
classRequest(models.Model):
user = models.ForeignKey(User)
view = models.CharField(max_length = 250)
visits = models.PositiveIntegerField(default=0)
views.py
def daygaps(request,*a, **kw):
request_counter = Request.objects.get_or_create(
user = request.user, view = 'daygaps')
request_counter.visits += 1 # or =F('visits')+1 to avoid a race condition as suggested by Moses Koledoye
request_counter.save()
OR
models.py
classRequest(models.Model):
user = models.ForeignKey(User)
view = models.CharField(max_length = 250)
visits = models.PositiveIntegerField(default=1)
views.py
def daygaps(request,*a, **kw):
updated_count = Request.objects\
.filter(user= request.user, view='daygaps')\
.update(visits=F('visits')+1)
if not updated_count:
Request.objects.create(user= request.user, view='daygaps')
which avoids race conditions too and has an added advantage of not having to retrieve the object.
In general, I guess the second one is better if the update is simple enough to be implemented with F
expressions.
Solution 2:
Instead of using filter
and indexing the list returned by the QuerySet, you could simply use .get
to return the object:
from django.db.models import F
def daygaps(request,*a, **kw):
...
request_counter = Request.objects.get(
user__username = request.user.username, view = 'daygaps')
request_counter.visits = F('visits') + 1
request_counter.save()
You can wrap the logic in a try/except
to handle DoesNotExist
exceptions.
The F
expression helps you manage race conditions. Read more: Updating attributes based on existing fields
Post a Comment for "Django Model Not Updating"