0

I have a model:

class IceCream(db.Model):
    flavor = db.Column(db.Integer, default=2)

    licks = 0

    def update_licks(self):
        self.licks += 1

My goal is that I have some variables that are stored in the database, and others that aren't. However, licks keeps resetting to 0 every time I load the object. How can I fix this so the variable doesn't reset while the server is running?

Francisco
  • 10,918
  • 6
  • 34
  • 45
Tips48
  • 745
  • 2
  • 11
  • 26
  • Try assigning directly to the class itself instead of the instance, because the instance gets destroyed when the view is done rendering. Basically, instead of using the instance variable `self.licks`, assign directly to the class, i.e. `IceCream.licks`. – metatoaster Jun 13 '18 at 03:40

1 Answers1

1

What you are looking for is a static variable which won't be created everytime you create a new object. You did create a static variable. But, problem is you created an instance variable when you wrote self.licks. So, now you have two variable, one is a static variable named licks, which is accessible via IceCream.licks and other one is an instance variable which is accessible via self.licks inside an object. So, how to fix it is modify your code as below

class IceCream(db.Model):
    flavor = db.Column(db.Integer, default=2)

    licks = 0

    def update_licks(self):
        IceCream.licks += 1
rawwar
  • 4,834
  • 9
  • 32
  • 57