Home > Net >  How do i show related foreign key in django query set?
How do i show related foreign key in django query set?

Time:01-27

I'm new to django, and i want to show field that related to foreign key in another table. this is the table.

enter image description here

i want to career table got the career_tag_name and hex_code from table color. i've tried the Career.objects.raw() this is the query in views.py:

careers = Career.objects.raw('''SELECT website_career_tag.career_tag_name,website_color.hex_code, website_career.* 
from website_career INNER JOIN website_career_tag on website_career_tag.id = website_career.career_tag_id_id 
LEFT JOIN website_color on  website_career_tag.color_id_id = website_color.ID''')

it works perfectly, until i want to use filter() by career_tag_name. when i use query set it's more easy than make it raw to filter.

how do i make those raw query to query set?

CodePudding user response:

It's always better to use django's own ORM rather than raw query and it's quite easy as well. Django querysets always stores all related table informations everywhere, you should just reference to them from the object. For example for career list view you can get all career informations and select the related fields to make loops less expensive in templates:

careers = Career.objects.select_related('career_tag_id', 'career_tag_id__color_id')

And then in a template just refer to related objects as:

{% for career in careers %}
{{ career.career_tag_id.career_tag_name }}
{{ career.career_tag_id.color_id.color_name }}
{% endfor %}
  • Related