2

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.

1
  • If you apply appropriate 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. Commented Aug 13, 2016 at 19:08

1 Answer 1

1

Ignoring the fact that it is not database efficient to do this, the easiest way is to just make sure you are accessing the reversed Foreign Key relationships correctly.

Do something like this:

{% for city in all_cities %}
  ...blah blah blah
    {% for portfolio in city.portfolio_set.all %}
      ... Blah blah
        {% for property in portfolio.property_set.all %}
          ... More blah

And you should be good to go

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.