2π
β
I donβt see a need to use distinct
here. By representing the states as separate model and using relations you would gain much more flexibility.
I suggest you create a third State
model and use a ForeignKey to relate the models together so that each Market
has a one to many relation to single State
, i guess you also want Location
model related to the Market
model.
class State(models.Model):
name = models.CharField('State name', max_length=150)
class Market(models.Model):
name = models.CharField('Market name', max_length=150)
state = models.ForeignKeyField(State)
class Location(models.Model):
state = models.ForeignKeyField(Market)
...
In your view, all you need to do is take all the states and pass them into the template:
def locations_landing(request):
state_list = State.objects.all()
return render_to_response('locations.html', {'state_list':state_list})
And finally, in your template, iterate over the state list and use a backward relation queryset to get all the markets in that state:
{% for state in state_list %}
<h4>{{ state }}</h4>
{% for market in state.market_set.all %}
<p>* <a href="#">{{ market }}</a></p>
{% for location in market.location_set.all %}
<p> {{ location }} </p>
{% endfor %}
{% endfor %}
{% endfor %}
π€Davor Lucic
Source:stackexchange.com