unbound method save() must be called with MyModel instance as first argument

63 views
Skip to first unread message

Tom Tanner

unread,
Jan 23, 2018, 7:43:18 PM1/23/18
to Django users
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()`?

Costja Covtushenko

unread,
Jan 23, 2018, 7:59:11 PM1/23/18
to django...@googlegroups.com
Hi,

It looks like with get_model() you’ve gotten Model class not Model instance.
You can use `save()` on instance only.
You need to have something like:

class_ = get_model(…)
instance = class_()
instance.save()

I hope that make sense to you.

Regards,
C.

On Jan 23, 2018, at 7:43 PM, Tom Tanner <dontsende...@gmail.com> wrote:

get_model

Tom Tanner

unread,
Jan 23, 2018, 9:18:46 PM1/23/18
to Django users
In my case, I'm using `setattr()` because I need to access a field via string and set it. I can't do `obj.myCol = "blah blah"` because this whole code is part of a `manage.py` command I'm setting up that asks the user to input the name of the model and column they want to add a new record for.

Costja Covtushenko

unread,
Jan 23, 2018, 9:30:24 PM1/23/18
to django...@googlegroups.com
Hi,

I did not mention your use of `stattr()`.
I was about class VS instance of that class.

Did you say that problem is with unbound method `save()` which should be called with instance as a first argument?

Regards,
C

-- 
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/f06c409b-ca0a-4350-8736-26ad0553ab67%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Costja Covtushenko

unread,
Jan 23, 2018, 9:34:18 PM1/23/18
to django...@googlegroups.com
Also it looks like in your separate tread Daniel wrote:

> model_instance = model()

That is how you can create instance from model.

Regards,
C
Reply all
Reply to author
Forward
0 new messages