简体   繁体   English

django:基本模型的子类名称

[英]django: subclass name from base model

Want to access my subclass name from the base model: 要从基本模型访问我的子类名称:

class Asset(models.Model):
    name = models.CharField(max_length=50, blank=False)
    country = models.ForeignKey(Country)
    industry = models.ForeignKey(Industry)
    ric = models.CharField(max_length=50, blank=False)
    notes = models.TextField(blank=True)

    def __unicode__(self):
        return "%s - %s" % (self.name, self.__class__.__name__)


class Equity(Asset):
    ticker = models.CharField(max_length=6, blank=False)
    start_of_day = models.TimeField(default=None, null=True, blank=True, help_text="Start time to query TR")
    query_frequency = models.IntegerField(help_text="In seconds, timeinterval between checks (intraday))")
    end_of_day = models.TimeField(default=None, null=True, blank=True, help_text='End time to query TR')

    class Meta:
        verbose_name_plural = "Equities"


class CashManagementInstrument(Asset):
    currency = models.ForeignKey(Currency)
    rate = models.DecimalField(max_digits=12, decimal_places=4)
    maturity_date = models.DateTimeField(default=datetime.now, blank=False)

    class Meta:
        verbose_name_plural = "Mutual Funds"

From my admin I have a model which has an Asset as related. 从我的管理员那里我有一个与资产相关的模型。 Just there, I want to get its name and its sub-class, ej: 就在那儿,我想知道它的名称和子类ej:

Apple - Equity 苹果-股票

Holding - CashManagementInstrument 控股-现金管理工具

Thanks 谢谢

finally i've resolved my problem in this way, this IS NOT the most elegant way to do it but it works :) 终于我以这种方式解决了我的问题,这不是最优雅的方式,但是它有效:)

class Asset(models.Model):
name = models.CharField(max_length=50, blank=False)
country = models.ForeignKey(Country)
industry = models.ForeignKey(Industry)
ric = models.CharField(max_length=50, blank=False)
notes = models.TextField(blank=True)

def __unicode__(self):
    return "%s - %s" % (self.get_child_asset(), self.name)

def get_child_asset(self):
    if hasattr(self, 'equity'):
        return "Equity"
    elif hasattr(self, 'realstate'):
        return "Real State"
    elif hasattr(self, 'fixedincome'):
        return "Fixed Income"
    elif hasattr(self, 'mutualfunds'):
        return "Mutual Funds"
    elif hasattr(self, 'cashmanagementinstrument'):
        return "CMI"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM