Reputation: 3663
I'm using setattr()
to set attributes of a new object of a Django model.
obj = apps.get_model(app_label="theme", model_name="MyModel")
setattr(obj,"myCol",100)
obj.save()
I got this error: TypeError: unbound method save() must be called with DataPopulationTracts2016 instance as first argument (got nothing instead)
.
I want to save the new instance of MyModel
to the model, using get_model()
and setattr()
to make a new instance of the model and set its attributes. How do I make get_model()
and setattr()
work with save()
?
EDIT: To clarify, I'm making a manage.py command where the user inputs the model and column they want to add a new record for.
Upvotes: 1
Views: 379
Reputation: 363043
get_model
gets the model class. So you should create an instance:
Model = apps.get_model(app_label="theme", model_name="MyModel")
obj = Model()
setattr(obj,"myCol",100)
obj.save()
Note: I'm assuming you've created a simplified example here. However, if you don't really need the extra dynamism, you should really prefer to just do the vanilla:
MyModel.objects.create(myCol=100)
Upvotes: 2