我试图根据字典中包含的键、值对动态定义模型的字段。
我尝试了两种方法:
字典是:
NOTIFICATION_TYPES = {
'friend_request_received': 0,
'friend_request_accepted': 1,
# eccetera
}
非常错误的(生成异常,因为 self 没有定义):
class EmailNotification(models.Model):
"""
User Email Notification Model
Takes care of tracking the user's email notification preferences
"""
user = models.OneToOneField(User, verbose_name=_('user'))
for key, value in NOTIFICATION_TYPES.items():
setattr(self, key, models.BooleanField(_('notify new matches'), default=True))
class Meta:
db_table = 'profile_email_notification'
显然错误较少但不创建模型字段:
class EmailNotification(models.Model):
"""
User Email Notification Model
Takes care of tracking the user's email notification preferences
"""
user = models.OneToOneField(User, verbose_name=_('user'))
def __init__(self, *args, **kwargs):
for key, value in NOTIFICATION_TYPES.items():
setattr(self.__class__, key, models.BooleanField(_(key), default=True))
super(EmailNotification, self).__init__(*args, **kwargs)
class Meta:
db_table = 'profile_email_notification'
有可能做我想做的事吗?我确定是!