辞書に含まれているキーと値のペアに応じて、モデルのフィールドを動的に定義しようとしています。
私は2つの方法を試みました:
辞書は次のとおりです。
NOTIFICATION_TYPES = {
'friend_request_received': 0,
'friend_request_accepted': 1,
# eccetera
}
非常に間違っています(自己が定義されていないため、例外が生成されます):
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'
私がやろうとしていることをすることは可能ですか?きっとそうです!