0

I am saving the form data into a model instance. There are fields where the user can enter values from 0 and above or leave them empty. Now I should assign them to a field.

Eg code

def update(self, my_val):
    self.my_val = my_val or None

This above code works fine for values of 1 and above. But not for 0. How can I allow for 0 and positive numbers and if my_val is an empty string then I should store it as None. How can I do that?

1
  • Both the answers worked but I am selecting the one liner answer because the if condition in that is sufficient for my case since there will be only empty string or 0 and not other falsy values. Commented Mar 24, 2021 at 3:20

2 Answers 2

2

You can use the ternary operator in Python.

def update(self, my_val):
    self.my_val = None if my_val=='' else my_val

This will store None if it is empty string(that is what mentioned in Question), otherwise it will store it as it is.

Sign up to request clarification or add additional context in comments.

Comments

2

Likely it is more readable here to work with an if check, so:

def update(self, my_val):
    if not my_val and my_val != 0:
        self.my_val = None
    else:
        self.my_val = my_val

The reason this happens is because the … or … first checks the first operand and if the truthiness is False, it returns the second operand. Since the empty string, None, and 0 all have truthiness False, it thus means that it will in that case use None.

1 Comment

thanks for the clear explanation. I understood it now.

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.