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?

3
  • Does this answer your question? assigning class variable as default value to class method argument Commented Oct 19, 2022 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. Commented Oct 19, 2022 at 23:08
  • @NickODell great explanation! Now everything is perfectly clear Commented Oct 21, 2022 at 8:52

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

1 Comment

I did it in my code, but I was hoping to make it simplier. But now I hope it helps other noobies ;D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.