3

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.

2
  • Will the table_name will be same as model class name always? Commented Jul 19, 2020 at 16:20
  • @ArakkalAbu Yes, but I didn't want to parse the input string as python code because it'll introduce security issues. Commented Jul 19, 2020 at 18:08

3 Answers 3

4

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]
Sign up to request clarification or add additional context in comments.

1 Comment

Oooooh okay, so I actually just replaced the selected model class. It works for the first iteration, but not the rest. I was trying to condense the number of variables, but that was the wrong condensation.
3

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.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.