flywheel icon indicating copy to clipboard operation
flywheel copied to clipboard

Feature Suggestions: Option to set to default value when None and option to treat "" as None.

Open justinoue opened this issue 9 years ago • 2 comments

When a field is set to None due to an explicit None value, there could be the option to set it to its default value before validation/

I've written a field validator loop (https://github.com/mathcamp/flywheel/issues/29) and I've just recently added this check to it. Ideally you would want to check if nullable is false first but it looks like nullable isn't an attribute (it's just part of the init to append the not null check.)

It might be possible to do what I propose in a check method, but python isn't my strongest language.

  def validate(self):
    self._fields_with_errors = []
    for field in self.meta_.fields.values():
      try:
        #check if the field's value is None and if it has a default, if it's none, set it to it's default.
        if field.resolve(self) is None and field.default is not None:
          setattr(self, field.name, field.default)

        field.validate(self)
      except ValueError as e:
        res = re.search('Validation check on field (.*) failed for value (.*)', str(e))
        self._fields_with_errors.append(res.group(1))
    return len(self._fields_with_errors) == 0

My other suggestion is to treat "" as None for the nullable check for str field types. Or to at least have that option. This one's not a big deal and can easily be overcome with a check.

lambda x: x != ""

justinoue avatar Mar 12 '16 14:03 justinoue

These are some good feature ideas. I'm a bit hosed at the moment, but I will give this some thought and try to find the best way to get that functionality in there. Probably won't have any time to start working on this until next Monday at the earliest.

stevearc avatar Mar 16 '16 06:03 stevearc

👍 would be great to have a mechanism similar to SQLAlchemy for setting default value e.g

state = Field(nullable=False, default=StateEnum.CREATED)

adamhadani avatar Apr 22 '16 16:04 adamhadani