【问题标题】:get sub class type from abstract base class in django从 django 中的抽象基类获取子类类型
【发布时间】:2013-10-13 22:30:08
【问题描述】:

我有一个名为 Notification 的抽象类。我有 2 个具体的实现,即 NearNotification 和 FarNotification。

每个都有不同的实体与之关联。一个是部门,一个是组。

我想向与 NearNotification 的部门或 FarNotifications 的组关联的电子邮件发送电子邮件。

现在我的抽象通知类看起来像:

class Notification(models.Model):
    name = models.CharField(max_length=256)

    class Meta:
        abstract = True

    def send(self):
        group_email = self.group.email
        department_email = self.department.email      

根据创建的类、部门或组,填充部门或组字段。

如何有条件地对该子类进行排序以确定要使用的电子邮件?

有点像

def send(self):
     if concrete class = FarNotification:
          group_email = self.group.email
     elif if concrete class = NearNotification: 
          department_email = self.department.email

【问题讨论】:

  • This 问题会帮助你

标签: django django-models abstract-class


【解决方案1】:

你可以通过self访问类名:

def send(self):
     if self.__class__.__name__ = "FarNotification":
          group_email = self.group.email
     elif if self.__class__.__name__ = "NearNotification": 
          department_email = self.department.email

【讨论】:

    猜你喜欢
    • 2018-11-19
    • 1970-01-01
    • 1970-01-01
    • 2011-06-18
    • 2022-06-16
    • 1970-01-01
    • 2011-01-11
    • 1970-01-01
    • 2018-08-23
    相关资源
    最近更新 更多