S
S
s_katala2018-05-11 18:06:19
Django
s_katala, 2018-05-11 18:06:19

Why is the view counter not working?

class Post(models.Model):
  views = models.IntegerField(("View count"), default=0, editable=False)

  def viewed(self):
   self.views += 1
   self.save(update_fields=['views'])

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Roman Kitaev, 2018-05-11
@deliro

Your version should work, but the correct one is:

def viewed(self):
    type(self).objects.filter(id=self.id).update(views=F('views') + 1)

A
Alex Meyer, 2018-05-14
@iriddy

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'])

Take a look at the parameter editable = False.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question