Is there a way to autoexecute methods on models?

Is there a way to use constructor type methods in model classes? For example, I have a CharField with the intention of entering comma separated words. Then a custom method splits the string and corrects capitalization or other formatting, then stores the list in a non-field variable in the model class, so it can be called easily in a template without having to process the string on each call, just have the list created whenever the model is first created, basically like a constructor would do.

First, a “non-field variable” in the model class is not persisted. If you’re only wanting to perform this pre-processing once when the data is entered, then it does need to be a field for it to be available in subsequent references. Otherwise, you would need to perform this processing every time that row is read from the database.

There are two different places where it could be appropriate to do this work. First, you could do it within your form handler. When you’re processing the input from the form, you could populate the field from the data submitted in the other field.

Or, you could override the save method in the model to do the same thing.

But, neither of these is perfect, and both create situations where it’s possible that this new field ends up out-of-sync with the raw data entered.

If you want to make sure that the raw data is always converted, you can include a model method that will return the post-processed value. That method could check to see if the raw value has already been processed, and if so, retrieve the processed value. (If not, process the value and save it.)

But, and this is an important point here - this will not save this value across different invocations of that page. If you go to that page, it will process the raw data. If you hit refresh, the new invocation of that view will get a new copy of the model instance, and so need to reprocess the raw data.

(I guess I ought to add the standard disclaimer at this point - Unless there’s a really significant amount of processing that needs to be done, this is much worry about nothing. Unless I had a specific indication that the processing involved in this data was causing problems, the time you’ll save by doing this is probably negligible in the grand scheme of things.)

1 Like

Okay thank you, that does clear up what I was asking