Having a bit of trouble getting my Django app to display how I'd like it. My model looks like this:
class City (models.Model):
city_name = models.CharField(max_length=100, unique=True)
def __str__(self):
return self.city_name
class Portfolio(models.Model):
portfolio_name = models.CharField(max_length=20, unique=True)
city = models.ForeignKey(City, db_constraint=False, on_delete=models.CASCADE)
def __str__(self):
return self.portfolio_name
class Property (models.Model):
portfolio = models.ForeignKey(Portfolio, db_constraint=False, on_delete=models.CASCADE)
prop_name = models.CharField(max_length=250, unique=True)
def __str__(self):
return self.prop_name
I want my template to display each City, and under each City have its Portfolios, and under each portfolio have its Properties. I'm a bit new to Django, coming from AngularJS where I could do it like this to throw filters in my loops(obviously doesn't work in Django, at least how I'm doing it):
<ul>
{% for city in all_cities %}
<li>
{{ city.city_name }}
<ul>
{% for portfolio in all_portfolios| portfolio.city = city %}
<li>
{{ portfolio.portfolio_name }}
<ul>
{% for property in portfolio.all_properties| property.portfolio = portfolio%}
<li>
{{ property.prop_name }}
</li>
{% endfor %}
</ul>
</li>
{% endfor %}
</ul>
</li>
{% endfor %}
</ul>
Any ideas? There is probably a simple solution that I just can't verbalize yet. The only thing I've found to do it like this is to create a custom queryset for each city, then for each portfolio, but there has to be a better way to do this.
prefetch_related()calls to the query set before finalizing it, you should be able to naively do the nested iteration in the template without causing further database access.