简体   繁体   中英

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

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

在此处输入图像描述

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?

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 %}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM