Flash
Flash

Reputation: 16713

Force exception to be raised when setting invalid field on model instance

If I accidentally typo the field name on a model, I want to raise an exception rather than silently failing:

obj = MyModel()
obj.fieldsdoesnotexist = 'test' # No exception is raised

How can I make Django raise exceptions when setting invalid fields?

Upvotes: 0

Views: 312

Answers (1)

Dima  Kudosh
Dima Kudosh

Reputation: 7376

You can achieve this by creating Mixin that overrides setattr behavior like this:

class ValidateFieldNamesMixin:
    def __setattr__(self, name, value):
        if not hasattr(self, name):
            raise ValueError('Invalid field name!')
        return super().__setattr__(name, value)

And you must inherit this mixin in your MyModel class:

class MyModel(ValidateFieldNamesMixin, Model):
    # etc

Upvotes: 2

Related Questions