By writing down the django request and getting the back related objects in a single database hit!

I wrote these models in models.py:

class User (models.Model):
    first_name = models.CharField (max_length = 80)

class Skill (models.Model):
    user = models.ForeignKey (User)
    title = models.CharField (max_length = 80)
    level = models.IntegerField (default = 3)

class Work (models.Model):
    user = models.Foriegnkey (User)
    work_name = models.CharField (max_length = 80)
    salary = models.IntegerField ()

now I want to get those Jobs from the database that certain users have and visualize html with them. I am writing this code in views.py:

def show_works (request, skill):
    works = Work.objects.select_related (). filter (user__skill__title = skill)
    return render_to_response ("works.html", {'works': works})

but there is one more thing that I want to show in this html: I want to show the first_name of the user of this work and his skills. I used select_related (), but I can only show first_name, but I cannot achieve user skills.

I want to write an optimal query to get work and other additional information, such as the user and the skills of this user! like a punch of code: (I do not want to delete the database for each job in order to get its user skills)

template works.html:

{% for work in works%}
    
        {{work.work_name}}
        user is: {{work.user.first_name}}
        which has these skills:
        {% for skill in work.user.skill%}
             {{skill.title}} 
        {% endfor%}
    
{% endfor%}
+5
1

, , , .

, :

{% for skill in work.user.skill_set.all %}
    {{skill.title}}
{% endfor %}
+3

All Articles