Skip to main content
 首页 » 编程设计

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

2024年10月25日36youxin

我为 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 

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

有没有办法实现这种灵 active ?

请您参考如下方法:

您可以使用与实例化相同的**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')