B
B
bituke2021-07-26 17:52:17
Django
bituke, 2021-07-26 17:52:17

How to get all object data in django in template engine?

Good day.
The task is as follows:

There is a client model:

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

There is a portfolio model:
class Portfolio(models.Model):
  client = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='portfolio')
  name = models.CharField('название', max_length=255)

There is a stock model that is associated with a portfolio.
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')

And of course there is the ticker model that the stock is associated with.
class Ticker(models.Model):
  name = models.CharField(max_length=255)

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

The task is as follows:
There is a django template engine loop that prints all clients:
{% for i in clients %}
    {{ i.name }}
{% endfor %}

And in this loop, you need to output the sum of all TickerValue.closing_cost for the last day, which belongs to the ticker, which belongs to the stock, which belongs to the portfolio, which belongs to the client in the cycle.
Interested in any way to solve this problem. I would be infinitely grateful if you give a direction where you can dig, I tried to write functions under the model - it was not possible to filter objects. Thank you very much in advance.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2021-07-26
@bituke

{% for client in clients %}
    {% for portfolio in client.portfolio_set.all %}
        {% for stock in portfolio.stock_set.all %}
             {% for ticker_value in stock.ticker.tickervalue_set.all %}
                  {{ ticker_value.closing_cost }}
             {% endfor %}
        {% endfor %}
    {% endfor %}
{% endfor %}

You should look into other types of relationships besides the foreign key.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question