1

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!

ray6080
  • 873
  • 2
  • 10
  • 25

2 Answers2

1

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.

Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • If we use obj = Model1(**params), won't it be obj = Model1('attr1'=params['attr1'], …) ? I mean, it turns to string. – ray6080 Mar 14 '14 at 02:58
  • @ray6080, Nope, it would be like `Model1(attr1=params['attr1'],..)` - like normal keyword arguments. – alecxe Mar 14 '14 at 03:00
0

I prefer something like this

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

obj = Model1(**params)
erthalion
  • 3,094
  • 2
  • 21
  • 28
  • If we use obj = Model1(**params), won't it be obj = Model1('attr1'=params['attr1'], …) ? I mean, it turns to string. – ray6080 Mar 14 '14 at 02:58
  • No, as @alecxe said see http://stackoverflow.com/questions/1769403/understanding-kwargs-in-python – erthalion Mar 14 '14 at 02:59