How to create different objects depending on input?

Viewed 115

What I have so far:

import app.models as models

if table_name ==  "Appliances":
    model = models.Appliances
elif table_name == "ArtsCraftsAndSewing":
    model = models.ArtsCraftsAndSewing
...

for index, row in df.iterrows():
    model = model(param1=row[column1], param2=row[column2], ...)
    model.save()

TypeError: 'Appliances' object is not callable

Basically I'm trying to call model = models.Appliances(param1=row[column1], param2=row[column2], ...) except the specific object changes depending on input.

Edit: Appliances and ArtsCraftsAndSewing have the same parameters.

3 Answers

By writing:

model = model(…)

in the second iteration, model no longer refers to the model, but now to an object of that model. You should change the name of the object, for example:

for index, row in df.iterrows():
    model_object = model(param1=row[column1], param2=row[column2], …)
    # …

You might want to use a dictionary to do the mapping:

models = [models.Appliances, models.ArtsCraftsAndSewing]
model_dict = {
    m.__name__: m for m in models
}
model = model_dict[table_name]

You can use getattr() here,

from app_name import models

table_name = 'Appliances' # or something else
ModelKlass = getattr(models, table_name)

for index, row in df.iterrows():
    model_instance = ModelKlass(param1=row[column1], param2=row[column2], ...)

Note: I assume table_name will be the Django model name.

Just create a dictionary of all the different model types and pass your inputs as keys:

model_types = dict('appliances' = Appliances, 'arts_crafts_and_sewing' = ArtsCraftsAndSewing)

your_object = model_types[type](param1=arg1, param2=arg2, ...) // here `type` is your input which you can enter via some form or whatever.
Related