2016-07-10 6 views
2

からサブクラス名は、ベースモデルからの私のサブクラス名にアクセスしたい:私の管理者からジャンゴ:ベースモデル

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" 

を、私は、関連資産を持っているモデルがあります。

+1

の可能性のある重複した[Djangoのモデルのサブクラス:スーパークラスを照会することによって、サブクラスを取得します](のhttp:// stackove rflow.com/questions/3109461/django-model-subclassing-get-the-subclass-by-querying-the-superclass) – Selcuk

答えて

0

は最終的に私はこのように私の問題を解決したCashManagementInstrument

おかげ - エクイティ

ホールディング -

アップル:ちょうどそこに、私はその名前とそのサブクラス、EJを取得したいです、これはそれを行うための最もエレガントな方法はありませんが、それは動作します:)

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"