I am trying to write a class that takes an instance of a Model from my app as an argument in its __init__
.
While reading up on the subject, I stumbled upon this quesiton: django: best practice way to get model from an instance of that model which argues that simply using type(instance)
would be the best way to go.
As tempting as it may be to use this right away, wouldn't using isinstance(instance, model)
be a better solution?
Say, for example (from my own code):
from app_name.models import Model1, Model2, ... ModelN
MODELS = (Model1, Model2 ... ModelN)
and then inside the class itself (in my case, Graph), do something like this:
class Graph():
model_instance = None
model = None
def __init__(self, model_instance):
if isinstance(model_instance, MODELS):
for a_model in MODELS:
if isinstance(model_instance, a_model):
self.model = a_model
self.model_instance = model_instance
...
As a beginner, I thought this was the best way I could come up with but also assume there are smoother/better ways of doing this. Possibly an even more "readable" way maybe? Pros? Cons?
Appreciate ALL feedback on this! Thanks!
Those interested in the whole context of this question, please check out my project on GitHub: https://github.com/VBoB13/TeachAdmin You can find the file with above code here: https://github.com/VBoB13/TeachAdmin/blob/master/teachadmin/graph.py