0

I need a model method with parameter with default value:

class MyModel(models.Model):
    parameter1 = models.DecimalField(max_digits=8,decimal_places=6, default=0)

    def my_method(self, parameter = parameter1)
        return parameter

But it doesn't work

Ideas?

Tomasz Brzezina
  • 1,452
  • 5
  • 21
  • 44
  • Does this answer your question? [assigning class variable as default value to class method argument](https://stackoverflow.com/questions/15189245/assigning-class-variable-as-default-value-to-class-method-argument) – Nick ODell Oct 19 '22 at 23:06
  • 2
    The short version is that Python evaluates the value of a default variable once, when the method is defined, not when the method is executed. So having a default value from the class is not possible. The next best thing is to have it default to None and replace None with the value you want. – Nick ODell Oct 19 '22 at 23:08
  • @NickODell great explanation! Now everything is perfectly clear – Tomasz Brzezina Oct 21 '22 at 08:52

1 Answers1

1

read @Nick ODell's comment, he's much smarter than me

but just add a little if!

class MyModel(models.Model):
    parameter1 = models.DecimalField(max_digits=8,decimal_places=6, default=0)

    def my_method(self, parameter = None)
        if parameter != None:
            return parameter
        return self.parameter1

        # or if you don't plan on passing 0 (zero)
        return parameter if parameter else self.parameter1
Nealium
  • 2,025
  • 1
  • 7
  • 9