【问题标题】:Dynamically set class attributes (model fields) while iterating a dictionary在迭代字典时动态设置类属性(模型字段)
【发布时间】:2013-03-17 13:16:30
【问题描述】:

我正在尝试根据字典中包含的键值对动态定义模型的字段。

我尝试了两种方法:

字典是:

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'

有可能做我想做的事吗?我敢肯定!

【问题讨论】:

    标签: python django django-models python-2.7


    【解决方案1】:

    你可以使用类装饰器:

    def add_notification(cls):
        for key in NOTIFICATION_TYPES:
            setattr(cls, key, models.BooleanField(_('notify new matches'), default=True))
        return cls
    
    @add_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'))
    
        class Meta:
            db_table = 'profile_email_notification'
    

    【讨论】:

      【解决方案2】:

      您需要在定义类之后设置这些额外属性:

      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'))
      
          class Meta:
              db_table = 'profile_email_notification'
      
      
      for key, value in NOTIFICATION_TYPES.items():
          setattr(EmailNotification, key, models.BooleanField(_('notify new matches'), default=True))
      

      您可以使用 class decorator 将 for 循环包装到应用于类的函数中:

      def add_notification(cls):
          for key, value in NOTIFICATION_TYPES.items():
              setattr(cls, key, models.BooleanField(_('notify new matches'), default=True))
          return cls
      
      @add_notification
      class EmailNotification:
          # ...
      

      我有点担心 Django 元类处理想要处理这些字段,您可能需要添加额外的调用以使 EmailNotification._meta 结构了解您添加的额外字段。

      【讨论】:

        【解决方案3】:

        感谢答案中的建议,但缺少一个关键的概念。

        必须做两件事:

        setattr(myclass, key, field)
        myclass.add_to_class(key, field)
        

        这里有一个可行的解决方案:

        https://github.com/nemesisdesign/nodeshot/blob/7798f81d558791499039afab1c860483fe30dd77/nodeshot/community/notifications/models/user_settings.py#L6

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2022-08-16
          • 1970-01-01
          • 2019-08-23
          • 1970-01-01
          • 2019-01-05
          • 1970-01-01
          • 1970-01-01
          • 2012-10-23
          相关资源
          最近更新 更多