ray6080
ray6080

Reputation: 893

Simplify Django model save() expression

Here is the situation:

I have a Django model save() function like this:

obj = Model1(attr1=params['attr1'], attr2=params['attr2'], attr3=params['attr3'], …)

or this:

class MyClass():
    pass

my = MyClass()

…...

obj = Model2(attr1=my.attr1, attr2=my.attr2, attr3=my.attr3...)

totally more than twenty attributes.

It's a really long and non-fiendly expression. Better way to do this? Thanks!

Upvotes: 1

Views: 48

Answers (2)

erthalion
erthalion

Reputation: 3244

I prefer something like this

params = {
    'param1': param1,
    'param2': param2,
     ....
}

obj = Model1(**params)

Upvotes: 0

alecxe
alecxe

Reputation: 474191

You can use setattr():

obj = Model1()
for key, value in params.iteritems()
   setattr(obj, key, value)

or:

obj = Model1(**params)

Also see:

Hope that helps.

Upvotes: 1

Related Questions