[Django]-How to initialize variable amount of Django model fields at once?

2👍

You can use the same **kwargs magic as in the instantiating:

def fill_profile(self, **kwargs):
    for attr, value in kwargs.iteritems():
        setattr(self, attr, value)

And then call this method with named arguments:

se_profile.fill_profile(reputation=1234, link='http://example.com')

0👍

I think it’s a good idea to have a default value for each field so that you wouldn’t have to always check if a parameter exists or not.

def fill_profile(self, reputation=None, link=None, image=None):
        self.reputation = reputation
        self.link = link
        self.image = image

se_profile.fill_profile(image="http://a.com/a.jpg")
👤nima

Leave a comment