Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 1089925
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 16, 20262026-05-16T23:17:55+00:00 2026-05-16T23:17:55+00:00

I am somewhat new to Django and have searched for some simple examples of

  • 0

I am somewhat new to Django and have searched for some simple examples of creating objects with subobjects in views so that in templates I can have nested for loops.

Here is my models.py for this application…

from django.db import models
from django import forms

class Market(models.Model):
    name   = models.CharField('Market name', max_length=150)
    state  = models.CharField('State', max_length=2)

    def __unicode__(self):
        return self.name

class Location(models.Model):
    name   = models.CharField('Location name', max_length=150)
    address1  = models.CharField('Address 1', max_length=200)
    address2  = models.CharField('Address 2', max_length=200,blank=True)
    city   = models.CharField('City', max_length=100)
    state   = models.CharField('State', max_length=2)
    zip_code = models.CharField('ZIP', max_length=10)
    phone  = models.CharField('Phone', max_length=20)
    hours  = models.TextField('Hours of operation', max_length=255)
    quote_text = models.TextField('Customer quote', max_length=500)
    quote_by = models.CharField('Customer name', max_length=30)
    yelp_url = models.URLField('Yelp URL', max_length=300,blank=True)
    image_store = models.ImageField('Storefront image', upload_to='images/locations', max_length=300,blank=True)
    image_staff = models.ImageField('Staff image', upload_to='images/locations', max_length=300,blank=True)
    market  = models.ForeignKey(Market, verbose_name='Regional market', null=True)

    def __unicode__(self):
        return self.name

Markets data may look as follows…

id = 1
state = 'MO'
name = 'St. Louis - Central'

id = 2
state = 'MO'
name = 'St. Louis - West'

id = 3
state = 'IL'
name = 'Chicago - South'

id = 4
state = 'IL'
name = 'Chicago - North'

In my views.py I’d like to create an object with a list/array of grouped Market states (distinct) in descending order, each with a subarray of the individual Market names in that State in order to complete a nested forloop in the template.

The templating language in Django is really cool in how it prevents a ton of logic from residing betwixt the html, which I like. But I am still wrapping my head around both Python syntax and the need to create all objects exactly the way they need to iterate in the template.

Here’s what views.py looks like …

def locations_landing(request):
    marketList = Market.objects.values('state').order_by('-state').distinct()
    return render_to_response('locations.html', locals()) 

How to return an object so that my template can perform the following nested looping…

{% for st in stateList.all %}
    <h4>{{ st.state }}</h4>
    {% for mkt in stateList.marketList.all %}
        <p>* <a href="#">{{ mkt.name }}</a></p>
    {% endfor %}
{% endfor %}

This would result in the following rendered in html based on my data samples above…

<h4>MO</h4>
<p>* St. Louis - Central</p>
<p>* St. Louis - West</p>
<h4>IL</h4>
<p>* Chicago - South</p>
<p>* Chicago - North</p>

BTW, there are no errors in any of the .PY code samples above, all is well, I just need some guidance on creating the object correctly in the view so the template does it’s thing.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-16T23:17:56+00:00Added an answer on May 16, 2026 at 11:17 pm

    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 %}
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm somewhat new to Python, Django, and I'd like some advice on how to
Does VS2008 have somewhat C++0x standard support? DUPLICATE Visual Studio support for new C
I'm using Django/Python, but pseudo-code is definitely acceptable here. Working with some models that
I am somewhat new to transactional databases and have come across an issue I
I am somewhat new to using JPA -- I'll put that out there right
I'm somewhat new to Spring (using 3.0), so I'm hoping there is a simple
I am somewhat new to R and I have run into a point where
I will preface the question by saying that I am somewhat new to the
being somewhat new to xml, I see examples where scripts are embedded within xml.
So I am still somewhat new to PHP, MySQL, and Javascript but I have

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.