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

63 vues
Accéder directement au premier message non lu

Tom Tanner

non lue,
23 janv. 2018, 19:43:1823/01/2018
à 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

non lue,
23 janv. 2018, 19:59:1123/01/2018
à 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

non lue,
23 janv. 2018, 21:18:4623/01/2018
à 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

non lue,
23 janv. 2018, 21:30:2423/01/2018
à 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

non lue,
23 janv. 2018, 21:34:1823/01/2018
à 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
Répondre à tous
Répondre à l'auteur
Transférer
0 nouveau message