Answer the question
In order to leave comments, you need to log in
Answer the question
In order to leave comments, you need to log in
Your version should work, but the correct one is:
def viewed(self):
type(self).objects.filter(id=self.id).update(views=F('views') + 1)
If you are already working with the created database, then perhaps you are adding one to None. Add a check for None:
class Post(models.Model):
views = models.IntegerField(("View count"), default=0)
def viewed(self):
if self.views:
self.views += 1
else:
self.views = 1
self.save(update_fields=['views'])
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question