i have written 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 Works from database which their users have a certain skill, and render a html with them. i write 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 another thing i want to show in that html: i want to show first_name of the user of that work and his skills. i used select_related(), but i can only show first_name but i can't reach user's skills.
i want to write an optimal query to get the works and the other extra informations, like user and the skills of it user! like the code blow: ( i don't want to hit database for every work to get its user's 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 %}
You'll probably never look at this again, but I'll try to answer it anyway.
I would think that this should work:
{% for skill in work.user.skill_set.all %}
{{skill.title}}
{% endfor %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With