从django中的抽象基类获取子类类型(get sub class type from abstract base class in django)

编程入门 行业动态 更新时间:2024-10-28 18:33:12
从django中的抽象基类获取子类类型(get sub class type from abstract base class in django)

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

每个都有一个与它们相关的不同实体。 一个是部门,一个是集团。

我想发送一封电子邮件给与NearNotification部门或FarNotifications集团相关联的电子邮件。

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

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

I have an abstract class called Notification. I have 2 concrete implementations which are NearNotification and FarNotification.

Each has a different entity associated with them. One is a Department and one is a Group.

I want to send an email to an email associated with either a Department for a NearNotification or a Group for FarNotifications.

Right now my abstract Notification class looks like:

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

Depending on which class is created, Department or Group the department or Group field is populated.

How can I conditionally sort on this subclass to determine which email to use?

Something like

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

最满意答案

您可以使用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

You can access to the name of the class with 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

更多推荐

本文发布于:2023-04-27 23:16:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1329243.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:子类   抽象   类型   django   base

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!