如何一次初始化可变数量的 Django 模型字段?

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

我为 Stackexchange 用户获取一些数据并将其存储在我的 Django 模型中:

class StackExchangeProfile(models.Model):
    access_token = models.CharField(max_length=100)
    expires = models.IntegerField()
    reputation = models.IntegerField(null=True)
    link = models.URLField(null=True)
    image = models.URLField(null=True)
    ...

我正在用一对必需的参数实例化这个模型:

token = {'access_token': 'abcd123abcd123abcd123', 'expires': 1234}
se_profile = StackExchangeProfile(**token)

我想出了一个方法来设置非必需的:

class StackExchangeProfile(models.Model):
    ...
    def fill_profile(self, reputation, link, image):
        self.reputation = reputation
        self.link = link
        self.image = image

我不是很喜欢,因为它不允许我设置自定义属性集(例如声誉和 link 仅在用户没有图像的情况下)。

有没有办法实现这种灵活性?

您可以使用与实例化相同的 **kwargs 魔法:

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

然后使用命名参数调用此方法:

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

我认为为每个字段设置一个默认值是个好主意,这样您就不必总是检查参数是否存在。

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")