Siavosh
Siavosh

Reputation: 2354

Python Django models execute a join query

I am developing an application with Django framework and I'm new to it

I need to create a query that simply joins 2 tables( type and subType ) and then later on use the result in the views the models file looks like this:

 class Type(models.Model):
     name = models.CharField(max_length=60)
    description = models.CharField(max_length=200)       

 class SubType(models.Model):
    name = models.CharField(max_length=60)
    description = models.CharField(max_length = 200)
    Type = models.ForeignKey(Type)

And in home.html file I have : (I dropped out the bootstrap code to make it more readable )

   <ul>
        <li ><a href="/home" >Home Page</a></li>
        {% for type in all_types %}
        <li >
          <a href="#">{{ type.name }} </a>
            <ul >
                --The Inner Loop-- 
            </ul>               
        </li>  
        {% endfor %}                      
    </ul>

I need to create an list of types and then inside each type I need to create another list which contains the subTypes of each type

I have no idea how do I have to create the query inside the views.py

 def index(request):
       list_all_types = #Here I have to create a join query via django models
       t = loader.get_template('home.html');
       c = Context({
            'all_types' : list_all_types,
       });
       return HttpResponse(t.render(c));

So please let me know how do I have to make the query and replace the correct code with the comment part in views.py and what changes do I have to add to make to the home.html to make it enabled show all the subTypes instead of --inner loop in home.html

Thanks in advance

Upvotes: 2

Views: 166

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599620

You don't need to do anything in the view other than get the types:

types = Type.objects.all()

In the template, you just iterate over type.subtype_set.all:

        <ul>
            {% for subtype in type.subtype_set.all %}
                <li>{{ subtype.name }}</li>
            {% endfor %}
        </ul>

Note that this is well covered by the tutorial. (As is the use of the render shortcut rather than loading and rendering the template separately.)

(Actually, what I said at first was not quite true: for the sake of efficiency, you can add prefetch_related() to the Type query.)

Upvotes: 1

Related Questions