B
B
bituke2021-07-27 08:55:27
Django
bituke, 2021-07-27 08:55:27

How to call a model function using another model?

Good afternoon, there is a tickervalue model with a function that needs to be called from another model:

class TickerValue(models.Model):
  ticker = models.ForeignKey(Ticker, on_delete=models.CASCADE, related_name='ticker_value')
  date = models.DateField()
  closing_cost = models.FloatField()

  def get_total_value(self, client):
    today = datetime.now()
    today = datetime.strftime(today, '%Y-%m-%d')
    yesterday = datetime.now() - timedelta(1)
    yesterday = datetime.strftime(yesterday, '%Y-%m-%d')
    last_objects = self.filter(ticker__ticker__portfolio__client=client, date__range=[yesterday, today])
    value = 0
    for i in last_objects.closing_cost:
      value += i
    return value


The model I'm trying to call the function from:
class Client(models.Model):
  investmen = models.ForeignKey(InvestmentAdvisor, on_delete=models.CASCADE, related_name='client')
  name = models.CharField(max_length=255)

  def get_total_value(self):
    tickervalue = self.portfolio.stock.ticker.ticker_value.get_total_value(self)
    return tickervalue

I'm trying to call this function on model links, but I can't do it because 'RelatedManager' object has no attribute 'stock'.
Thanks in advance for any help.

Full code:
models.py
class Client(models.Model):
  investmen = models.ForeignKey(InvestmentAdvisor, on_delete=models.CASCADE, related_name='client')
  name = models.CharField(max_length=255)
  description = models.TextField(blank=True)
  date_of_birth = models.DateField()
  retirement_date = models.DateField()
  drawdown_behavior = models.PositiveSmallIntegerField(choices=DRAWDOWN_BEHAVIOR,)
  employment_status = models.PositiveSmallIntegerField(choices=EMPLOYMENT_STATUS,)

  def get_total_value(self):
    tickervalue = self.portfolio.stock.ticker.ticker_value.get_total_value(self)
    return tickervalue



  def __str__(self):
    return self.name

class Portfolio(models.Model):
  client = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='portfolio')
  name = models.CharField('название', max_length=255)
  initial_investment_amount = models.PositiveIntegerField('начальная сумма инвестиций',)
  investment_horizon = models.PositiveIntegerField('инвестиционный горизонт',)
  type_investor = models.PositiveSmallIntegerField('тип инвестора', choices=TYPE_INVESTOR)
  currency = models.PositiveSmallIntegerField('валюта', choices=CURRENCY)
  maximum_allowable_drawdown = models.PositiveIntegerField('максимально допустимая просадка',)
  type_according_risk_reward = models.PositiveSmallIntegerField('тип по соотношению риска/прибыли', choices=TYPE_RISK)
  focus = models.PositiveSmallIntegerField('фокус', choices=FOCUS)
  sector_blacklist = models.TextField(blank=True) 
  types_assets = models.TextField()
  ETF = models.PositiveSmallIntegerField(choices=ETF)
  investment_strategy = models.PositiveSmallIntegerField('инвестиционная стратегия', choices=INVESTMENT_STRATEGY)
  create_date = models.DateField(auto_now=True)
  active = models.BooleanField()

  def get_all_active(self):
    all_acive = self.objects.filter()


  def __str__(self):
    return self.name

  def get_type_investor(self):
    return TYPE_INVESTOR[self.type_investor][1]

  def get_focus(self):
    return FOCUS[self.focus][1]

  def get_investment_strategy(self):
    return INVESTMENT_STRATEGY[self.investment_strategy][1]

class Sector(models.Model):
  pass

class Ticker(models.Model):
  name = models.CharField(max_length=255)

  def __str__(self):
    return self.name

class TickerValue(models.Model):
  ticker = models.ForeignKey(Ticker, on_delete=models.CASCADE, related_name='ticker_value')
  date = models.DateField()
  closing_cost = models.FloatField()

  def get_total_value(self, client):
    today = datetime.now()
    today = datetime.strftime(today, '%Y-%m-%d')
    yesterday = datetime.now() - timedelta(1)
    yesterday = datetime.strftime(yesterday, '%Y-%m-%d')
    last_objects = self.filter(ticker__ticker__portfolio__client=client, date__range=[yesterday, today])
    value = 0
    for i in last_objects.closing_cost:
      value += i
    return value


  def __str__(self):
    return self.ticker.name


class Stock(models.Model):
  portfolio = models.ForeignKey(Portfolio, on_delete=models.CASCADE, related_name='stock')
  name = models.CharField(max_length=255, blank=True)
  ticker = models.ForeignKey(Ticker, on_delete=models.CASCADE, related_name='ticker')
  sector = models.CharField(max_length=255, blank=True)
  share = models.FloatField()

  def __str__(self):
    return self.ticker.name

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stefan, 2021-07-27
@bituke

You are clearly doing something wrong when you try to call a function through 3 connections Client -> Portfolio -> TickerValue -> get_total_value(
) in the Client (which is not good, because I am of the opinion that methods in models should only interact with the model itself, without affecting others), or, which seems more acceptable to me, take this functionality into a separate function, and call it in my views her.

PS

Вот вам если что для чтения материал по структуре и организации проекта на Django, там рассказано про сервисы, и почему их стоит выносить отдельно

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question